clearsilver-0.10.5/0000755001211700116100000000000010645505101011101 500000000000000clearsilver-0.10.5/README0000644001211700116100000000467010261037504011711 00000000000000************************************ * Clearsilver README ************************************ For more information, see the website: http://www.clearsilver.net/ This package includes Clearsilver, the CGI kit and HTML templating system. For information about building and installing, see the included INSTALL file. This package also includes tools which help you use Clearsilver, as well as a few examples. ************************************************************ *** Clearsilver * Clearsilver - This is our html template system and cgi kit. There are too many great things about clearsilver to list them all here, but here are some of the salient points: * get the html out of your code * loops, conditionals, macros, and stuff * cgi kit unifies query variable and cookie handling * super-easy to go from static mockup to dynamic page * run multiple front-ends on the same application code * super-fast C-library * unifies Query variable and cookie handling * language neutral (C,C++,Python,Ruby,Perl,Java,C#) * nice iterative page debugging/development features * generate static-data-driven page content without using any code * did I mention super-fast? Supported language information: README.python ************************************************************* *** Tools * trans.py This is our transparent translation system. It's based on how we did translation at Yahoo!. You leave all the english strings right in the clearsilver templates. trans parses the html and extracts your language strings into a translation database. You can then translate the strings using any means. (it includes tools for dump and loading per-language files for shipping to translators). Occasionally trans isn't smart enough to find your language strings, in this case you can manually extract them into static language string files and trans will automatically pick them up. When it comes time to ship, trans generates language-independent templates, and a set of language files from your database. ************************************************************* *** Examples * static.cgi This is a standalone binary which handles Clearsilver rendering of static content. This is a great way to play with clearsilver syntax before you start writing dynamic CGIs with it. This is also a great way to do webpage mockups with much more power than server side includes. See the INSTALL file for information about configuring this for use with apache. clearsilver-0.10.5/README.python0000644001211700116100000000410210261037504013217 00000000000000 ************************************************************ *** Python Environment Information * Python - we know it and love it * Apache - the defacto standard * PyApache/mod_python Either one is fine, the goal is to load all Python code once, before Apache forks. Then, for every web-request, Apache just makes a function call into the Python environment which serves the page. This is "really fast" as it gets rid of all of the parsing and loading of Python. Various versions of PyApache and mod_python have gained and lost and gained again the ability to do this well. We used a hacked version of PyApache way back when, I think mod_python does this out of the box today. ************************************************************ *** Python Tools * CSPage.py This is our "page rendering superclass". It's pretty simple and has nice machinery for some of the stuff talked about on this list. For example, it has nice debugging and redirect support, and it has a mechanism for mapping form submit buttons to method names. Here is an example of how the form stuff works:
class MyPage(CSPage): def setup(self): # this runs before everything else pass def display(self): # this is a regular non-submission render pass def Action_Foo(self): # this is run automatically when the Foo submit button is clicked pass * odb.py This is an object to relational database mapping tool. It makes interacting with SQL databases really easy. It gives you a place to put all your SQL code. It also could be changed to work with flat files as well. We have some nice hooks to connect this to Clearsilver, so rendering database data into webpages is really easy. Here is an example: rows = mydb.mytable.fetchAllRows() # fetch all rows rows.hdfExport("CGI.tabledata",ncgi.hdf) # export them into the dataset # it is also really easy to change rows: row = mydb.mytable.fetchRow( ('user', 'jeske') ) row.email = 'jeske at chat.net' row.save() clearsilver-0.10.5/INSTALL0000644001211700116100000001155410261037503012060 00000000000000******************************************** * * Clearsilver INSTALL * * http://www.clearsilver.net * * Brandon Long, David Jeske * ******************************************** 1) Compile ------------------------------------------------ Simplest case: # ./configure # make Options to configure: --disable-compression Disables HTML Compression support --enable-remote-debugger Enables remote X CGI debugging --disable-apache Disables building of apache 1.3.x module --with-apache=path Set location of Apache installation --disable-python Disables building of python module --with-python=path Set location of Python Includes --disable-perl Disables building of perl module --with-perl=path Set location of Perl binary --disable-ruby Disables building of ruby module --with-ruby=path Set location of Ruby binary --disable-java Disables building of java module --with-java=path Set location of J2SDK --disable-csharp Disables building of csharp module --with-csharp=path Set location of csharp --enable-gettext Enable gettext message translation --disable-compression: Currently, the CGI output code in the cgi kit automatically attempts to detect whether the remote browser can handle compressed data, and if it does, compresses the output for text/html. This is run-time configurable via Config.CompressionEnabled. Disabling it at compile time eliminates the dependency on libz. --enable-remote-debugger: The CGI kit contains code for remotely debuggin CGI programs by launching an X based debugger (such as xxgdb or ddd) at the X display you specify in the HTTP request. There are controls such as a configurable list of allowed displays, but remote debugging is disabled by default. --enable-gettext: Enables gettext message translation. Once enabled you have a new builtin function "_()". This function calls the function gettext (man 3 gettext). The rest of the --disable/--with either disable a specific module, or point ClearSilver at the right program to enable it. The configure script will simple not build any module it can't find the right versions of programs to build against. Alternatively, if you are making ClearSilver part of your build environment, you can simple delete whichever module directory you don't want, and the build will ignore it. For information about compiling on Windows under MingW and MSYS, see python/README.txt The csharp wrapper was built with Mono (www.go-mono.com) and should work with v0.24 and later (give or take). In theory, it should be fairly simple to get this working on MS.Net as well. 2) Install ------------------------------------------------ # make install The make install is relatively new, and just installs the libraries/header files (and probably the perl and python modules, but that's a guess) 3) Example 1, Apache static.cgi ---------------------------------- "static.cgi" is a simple binary which will allow you to write static HDF files, static ClearSilver templates, and render them. This is a good way to get started and learn the clearsilver model and syntax. Follow the steps below to install static.cgi into your Apache configuration and then read the documentation while playing with static files. http://www.clearsilver.net/docs/man_hdf.hdf Add the following to your Apache configuration and copy the Clearsilver static.cgi binary from cgi/static.cgi into your Apache cgi-bin directory. AddHandler cgi-script .cgi Action cs-handler /cgi-bin/static.cgi AddHandler cs-handler .cs Since any html file is a valid CS file, I also run with: AddHandler cs-handler .html * About static.cgi: static.cgi works by assuming that whatever file it was pointed at is a CS template. It first tries to load common.hdf in the same directory, then it tries to load some other hdf files, and then it parses and displays the template file. Ie, if its pointed at foo.cs, it will load common.hdf, try to load foo.cs.hdf, if that fails, it tries foo.hdf. If the hdf defines CGI.StaticContent, it will assume that's the real template file (which is how we use it on www.clearsilver.net, we just point at he .hdf files, which define StaticContent as a wrapper.cs, which includes another file defined in the .hdf file). 4) Example 2, imd image server ------------------------------------ "imd" is a simple image server written with C and clearsilver. The imd directory has a README on how to set up imd with Apache. 5) Example 3, using with Python ----------------------------------- The clearsilver python wrapper comes with CSPage.py. This file contains the CSPage superclass, and this file gives some pointers on how to use the cs handler via python. A much more thorough example is Scott Hassan's image_server, available from http://www.dotfunk.com/projects/image_server clearsilver-0.10.5/LICENSE0000644001211700116100000000123510527221146012032 00000000000000 This source tree contains source code from Neotonic. All files in this release are marked with their license terms. Files which are part of our public open-source toolkits are released under our Neotonic ClearSilver License. A few files are from other sources, and will include their respective copyrights and licenses. If you did not receive a copy of the Neotonic ClearSilver License with this kit, you can get one from: http://www.clearsilver.net/license.hdf Some source-kits received from Neotonic may contain licensed Neotonic source code. That source code is Copyright (C) Neotonic, and may not be used without express written permission of Neotonic. clearsilver-0.10.5/CS_LICENSE0000644001211700116100000000514710261037503012422 00000000000000 ClearSilver is available under the following license, derived from the Apache Software License v1.1 For alternative licensing, please contact the authors at blong@clearsilver.net ClearSilver Software License Version 1.0 Copyright (c) 2003 Brandon Long. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by Neotonic Software Corp. (http://www.neotonic.com/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "Neotonic" and "ClearSilver" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact clearsilver@neotonic.com. 5. Products derived from this software may not be called "ClearSilver", nor may "ClearSilver" appear in their name, without prior written permission of Brandon Long or Neotonic Software Corp. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NEOTONIC, INC., OR ITS CLEARSILVER CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of Brandon Long and Neotonic Software Corp. For more information on Neotonic, please see . Some of the concepts of this software are based on previous software developed by Scott Shambarger, Paul Clegg, and John Cwikla. The current authors wish to thank them for their efforts. clearsilver-0.10.5/rules.mk.in0000644001211700116100000000750210541666436013133 00000000000000############################################################ # # rules.mk is A U T O G E N E R A T E D # # you must edit: rules.mk.in # ############################################################ ## ## Global Makefile Rules ## ## Before including this file, you must set NEOTONIC_ROOT ## OSNAME := $(shell uname -rs | cut -f 1-2 -d "." | cut -f 1 -d "-") OSTYPE := $(shell uname -s) LIB_DIR = $(NEOTONIC_ROOT)/libs/ ## Installation Directories srcdir = @srcdir@ top_srcdir = @top_srcdir@ VPATH = @srcdir@ prefix = @prefix@ exec_prefix = @exec_prefix@ bindir = @bindir@ sbindir = @sbindir@ libexecdir = @libexecdir@ datadir = @datadir@ sysconfdir = @sysconfdir@ sharedstatedir = @sharedstatedir@ localstatedir = @localstatedir@ libdir = @libdir@ infodir = @infodir@ mandir = @mandir@ includedir = @includedir@ DESTDIR = cs_includedir = ${includedir}/ClearSilver ## NOTE: The wdb code in util will tickle a bug in SleepyCat 2.4.5, ## which ships with various versions of Linux as part of glibc. If you ## are going to use that code, you should compile against SleepyCat ## 2.7.7 instead USE_DB2 = 1 USE_ZLIB = 1 @USE_MINGW32@ PICFLG = -fPIC ifeq ($(OSTYPE),OSF1) PICFLG = endif ifeq ($(OSNAME),MINGW32_NT) PICFLG = endif ## -------------- base (Linux/Neotonic) options PYTHON_INC = @PYTHON_INC@ PYTHON_LIB = @PYTHON_LIB@ PYTHON_SITE = @PYTHON_SITE@ JAVA_PATH = @JAVA_PATH@ JAVA_INCLUDE_PATH = @JAVA_INCLUDE_PATH@ CSHARP_PATH = @CSHARP_PATH@ ## Programs @SET_MAKE@ INSTALL = @INSTALL@ CC = @CC@ MKDIR = mkdir -p RM = rm -f CPP = g++ JAVAC = $(JAVA_PATH)/bin/javac JAVAH = $(JAVA_PATH)/bin/javah JAR = $(JAVA_PATH)/bin/jar APXS = @APXS_PATH@ PYTHON = @PYTHON@ PERL = @PERL@ RUBY = @RUBY@ CPPFLAGS = -I$(NEOTONIC_ROOT) @CPPFLAGS@ CFLAGS = @CFLAGS@ -Wall $(CPPFLAGS) $(PICFLG) OUTPUT_OPTION = -o $@ LD = $(CC) -o LDFLAGS = -L$(LIB_DIR) @LDFLAGS@ LDSHARED = $(CC) -shared $(PICFLG) CPPLDSHARED = $(CPP) -shared $(PICFLG) AR = @AR@ cr RANLIB = @RANLIB@ DEP_LIBS = $(DLIBS:-l%=$(LIB_DIR)lib%.a) DBI_LIBS = -ldbi -ldl -lz LIBS = @LIBS@ LS = /bin/ls XARGS = xargs -i% BUILD_WRAPPERS = @BUILD_WRAPPERS@ EXTRA_UTL_OBJS = @EXTRA_UTL_OBJS@ EXTRA_UTL_SRC = @EXTRA_UTL_SRC@ ## I don't really feel like writing a configure thing for this yet ifeq ($(OSNAME),SunOS) LDSHARED = ld -G -fPIC endif ifeq ($(OSTYPE),Darwin) LDSHARED = $(CC) -bundle -flat_namespace -undefined suppress $(PICFLG) CPPLDSHARED = $(CPP) -bundle -flat_namespace -undefined suppress $(PICFLG) endif ## --------------win32 options ## ifeq ($(OSTYPE),WindowsNT) ## CFLAGS += -D__WINDOWS_GCC__ ## USE_DB2 = 0 ## USE_ZLIB = 0 ## # SHELL=cmd.exe ## LS = ls ## PYTHON_INC = -Ic:/Python22/include ## LDSHARED= dllwrap ## endif ## ## ## -------------- ## ## ifeq ($(OSTYPE),FreeBSD) ## XARGS = xargs -J% ## # This should work on freebsd... but I wouldn't worry too much about it ## USE_DB2 = 0 ## PYTHON_INC = -I/usr/local/include/python2.2 ## endif ## ## ifeq ($(USE_ZLIB),1) ## LIBS += -lz ## endif ## ## ifeq ($(USE_DB2),1) ## DB2_INC = -I$(HOME)/src/db-2.7.7/dist ## DB2_LIB = -L$(HOME)/src/db-2.7.7/dist -ldb ## CFLAGS += $(DB2_INC) ## endif .c.o: $(CC) $(CFLAGS) $(OUTPUT_OPTION) -c $< everything: depend all .PHONY: depend depend: Makefile.depends SOURCE_FILES := $(wildcard *.c) Makefile.depends: $(NEOTONIC_ROOT)/rules.mk Makefile @echo "*******************************************" @echo "** Building Dependencies " @echo "** OSNAME: $(OSTYPE)" @rm -f Makefile.depends @touch Makefile.depends @if test "x" != "x$(SOURCE_FILES)"; then \ for II in "$(SOURCE_FILES)"; do \ gcc -M -MG ${CFLAGS} $$II >> Makefile.depends; \ done; \ fi @echo "** (done) " DEPEND_FILE := $(shell find . -name Makefile.depends -print) ifneq ($(DEPEND_FILE),) include Makefile.depends endif clearsilver-0.10.5/Makefile0000644001211700116100000000657210645312520012474 00000000000000# # Neotonic Source Kit # # Copyright (C) 2001 Neotonic and Brandon Long # # NEOTONIC_ROOT = . include rules.mk SUBDIRS = util cs cgi $(BUILD_WRAPPERS) OUTDIRS = bin libs # These are blank here... but populated under automated build VERSION = RELEASE = all: cs $(BUILD_WRAPPERS) rules.mk: configure ./configure configure: configure.in ./autogen.sh cs: output_dir @for mdir in $(SUBDIRS); do \ if test -d $$mdir; then \ if test -f $$mdir/Makefile.PL -a ! -f $$mdir/Makefile; then \ cd $$mdir; $(PERL) Makefile.PL PREFIX=$(prefix); cd ..; \ fi; \ $(MAKE) -C $$mdir PREFIX=$(prefix); \ fi; \ done install: all ./mkinstalldirs $(DESTDIR)$(cs_includedir) ./mkinstalldirs $(DESTDIR)$(bindir) ./mkinstalldirs $(DESTDIR)$(libdir) ./mkinstalldirs $(DESTDIR)$(mandir)/man3 $(INSTALL) -m 644 ClearSilver.h $(DESTDIR)$(cs_includedir)/ $(INSTALL) -m 644 cs_config.h $(DESTDIR)$(cs_includedir)/ $(INSTALL) -m 644 man/man3/*.3 $(DESTDIR)$(mandir)/man3/ @for mdir in $(SUBDIRS); do \ if test -d $$mdir; then \ if test -f $$mdir/Makefile.PL -a ! -f $$mdir/Makefile; then \ cd $$mdir; $(PERL) Makefile.PL PREFIX=$(prefix); cd ..; \ fi; \ $(MAKE) -C $$mdir PREFIX=$(prefix) install; \ fi; \ done depend: @for mdir in $(SUBDIRS); do \ if test ! -f $$mdir/Makefile.PL; then \ $(MAKE) -C $$mdir depend; \ fi; \ done newdepend: killdepend @echo "*******************************************" @echo "** Building dependencies..." @for mdir in $(SUBDIRS); \ do $(MAKE) -C $$mdir depend; \ done killdepend: @echo "*******************************************" @echo "** Removing Old dependencies..." @find . -name "Makefile.depends" -print | $(XARGS) rm % .PHONY: man man: @mkdir -p man/man3 @for mdir in $(SUBDIRS); do \ scripts/document.py --owner "ClearSilver" --outdir man/man3/ $$mdir/*.h; \ done .PHONY: hdf hdf: @mkdir -p docs/hdf @for mdir in $(SUBDIRS); do \ scripts/document.py --hdf --owner "ClearSilver" --outdir docs/hdf/ $$mdir/*.h; \ done changelog: p4 changes -l ./... clean: -@for mdir in $(SUBDIRS); do \ $(MAKE) -C $$mdir clean; \ done distclean: -@for mdir in $(SUBDIRS); do \ $(MAKE) -C $$mdir distclean; \ done -@for mdir in $(OUTDIRS); do \ rm -rf $$mdir/*; \ done rm -f config.cache config.log config.status rules.mk cs_config.h rm -rf autom4te.cache output_dir: @for mdir in $(OUTDIRS); do \ mkdir -p $$mdir; \ done CS_DISTDIR = clearsilver-0.10.5 CS_LABEL = CLEARSILVER-0_10_5 CS_FILES = README README.python INSTALL LICENSE CS_LICENSE rules.mk.in Makefile acconfig.h autogen.sh config.guess config.sub configure.in cs_config.h.in mkinstalldirs install-sh ClearSilver.h CS_DIRS = util cs cgi python scripts mod_ecs imd java-jni perl ruby dso csharp ports contrib m4 cs_dist: @if p4 labels Makefile | grep "${CS_LABEL}"; then \ echo "release ${CS_LABEL} already exists"; \ echo " to rebuild, type: p4 label -d ${CS_LABEL}"; \ exit 1; \ fi; rm -rf $(CS_DISTDIR) p4 label $(CS_LABEL) p4 labelsync -l$(CS_LABEL) $(CS_FILES) $(addsuffix /..., $(CS_DIRS)) mkdir -p $(CS_DISTDIR) tar -cf - `p4 files $(CS_FILES) $(addsuffix /..., $(CS_DIRS)) | cut -d'#' -f 1 | sed -e "s|//depot/google3/third_party/clearsilver/core/||"` | (cd $(CS_DISTDIR); tar -xf -) $(MAKE) -C $(CS_DISTDIR) man distclean chmod -R u+w $(CS_DISTDIR) chmod -R a+r $(CS_DISTDIR) tar chozf $(CS_DISTDIR).tar.gz $(CS_DISTDIR) clearsilver-0.10.5/acconfig.h0000644001211700116100000000257610261037504012756 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * config file */ #ifndef __CS_CONFIG_H_ #define __CS_CONFIG_H_ 1 @TOP@ /* Enable support for HTML Compression (still must be enabled at run time) */ #undef HTML_COMPRESSION /* Enable support for X Remote CGI Debugging */ #undef ENABLE_REMOTE_DEBUG /********* SYSTEM CONFIG ***************************************************/ /* autoconf/configure should figure all of these out for you */ /* Does your system have the snprintf() call? */ #undef HAVE_SNPRINTF /* Does your system have the vsnprintf() call? */ #undef HAVE_VSNPRINTF /* Does your system have the strtok_r() call? */ #undef HAVE_STRTOK_R /* Does your system have the localtime_r() call? */ #undef HAVE_LOCALTIME_R /* Does your system have the gmtime_r() call? */ #undef HAVE_GMTIME_R /* Does your system have the mkstemp() call? */ #undef HAVE_MKSTEMP /* Does your system have regex.h */ #undef HAVE_REGEX /* Does your system have pthreads? */ #undef HAVE_PTHREADS /* Does your system have lockf ? */ #undef HAVE_LOCKF /* Does your system have Berkeley DB v2 ? */ #undef HAVE_DB2 /* Enable support for gettext message translation */ #undef ENABLE_GETTEXT @BOTTOM@ #endif /* __CS_CONFIG_H_ */ clearsilver-0.10.5/autogen.sh0000755001211700116100000000024710336777403013042 00000000000000#!/bin/sh # Run this to generate all the initial makefiles, etc. srcdir=`dirname $0` test -z "$srcdir" && srcdir=. aclocal -I m4 autoheader autoconf ./configure $* clearsilver-0.10.5/config.guess0000755001211700116100000011315010326267523013353 00000000000000#! /bin/sh # Attempt to guess a canonical system name. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 # Free Software Foundation, Inc. timestamp='2001-09-04' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Written by Per Bothner . # Please send patches to . # # This script attempts to guess a canonical system name similar to # config.sub. If it succeeds, it prints the system name on stdout, and # exits with 0. Otherwise, it exits with 1. # # The plan is that this can be called by configure scripts if you # don't specify an explicit build system type. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit 0 ;; --version | -v ) echo "$version" ; exit 0 ;; --help | --h* | -h ) echo "$usage"; exit 0 ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi dummy=dummy-$$ trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. set_cc_for_build='case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int dummy(){}" > $dummy.c ; for c in cc gcc c89 ; do ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 ; if test $? = 0 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; rm -f $dummy.c $dummy.o $dummy.rel ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # Netbsd (nbsd) targets should (where applicable) match one or # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # Determine the machine/vendor (is the vendor relevant). case "${UNAME_MACHINE}" in amiga) machine=m68k-unknown ;; arm32) machine=arm-unknown ;; atari*) machine=m68k-atari ;; sun3*) machine=m68k-sun ;; mac68k) machine=m68k-apple ;; macppc) machine=powerpc-apple ;; hp3[0-9][05]) machine=m68k-hp ;; ibmrt|romp-ibm) machine=romp-ibm ;; *) machine=${UNAME_MACHINE}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE}" in i386|sparc|amiga|arm*|hp300|mvme68k|vax|atari|luna68k|mac68k|news68k|next68k|pc532|sun3*|x68k) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep __ELF__ >/dev/null then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit 0 ;; alpha:OSF1:*:*) if test $UNAME_RELEASE = "V4.0"; then UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` fi # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. cat <$dummy.s .data \$Lformat: .byte 37,100,45,37,120,10,0 # "%d-%x\n" .text .globl main .align 4 .ent main main: .frame \$30,16,\$26,0 ldgp \$29,0(\$27) .prologue 1 .long 0x47e03d80 # implver \$0 lda \$2,-1 .long 0x47e20c21 # amask \$2,\$1 lda \$16,\$Lformat mov \$0,\$17 not \$1,\$18 jsr \$26,printf ldgp \$29,0(\$26) mov 0,\$16 jsr \$26,exit .end main EOF eval $set_cc_for_build $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null if test "$?" = 0 ; then case `./$dummy` in 0-0) UNAME_MACHINE="alpha" ;; 1-0) UNAME_MACHINE="alphaev5" ;; 1-1) UNAME_MACHINE="alphaev56" ;; 1-101) UNAME_MACHINE="alphapca56" ;; 2-303) UNAME_MACHINE="alphaev6" ;; 2-307) UNAME_MACHINE="alphaev67" ;; 2-1307) UNAME_MACHINE="alphaev68" ;; esac fi rm -f $dummy.s $dummy echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` exit 0 ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit 0 ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit 0 ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit 0;; amiga:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit 0 ;; arc64:OpenBSD:*:*) echo mips64el-unknown-openbsd${UNAME_RELEASE} exit 0 ;; arc:OpenBSD:*:*) echo mipsel-unknown-openbsd${UNAME_RELEASE} exit 0 ;; hkmips:OpenBSD:*:*) echo mips-unknown-openbsd${UNAME_RELEASE} exit 0 ;; pmax:OpenBSD:*:*) echo mipsel-unknown-openbsd${UNAME_RELEASE} exit 0 ;; sgi:OpenBSD:*:*) echo mips-unknown-openbsd${UNAME_RELEASE} exit 0 ;; wgrisc:OpenBSD:*:*) echo mipsel-unknown-openbsd${UNAME_RELEASE} exit 0 ;; *:OS/390:*:*) echo i370-ibm-openedition exit 0 ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit 0;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit 0;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit 0 ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit 0 ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit 0 ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit 0 ;; i86pc:SunOS:5.*:*) echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit 0 ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit 0 ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit 0 ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit 0 ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(head -1 /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit 0 ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit 0 ;; sparc*:NetBSD:*) echo `uname -p`-unknown-netbsd${UNAME_RELEASE} exit 0 ;; atari*:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit 0 ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit 0 ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit 0 ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit 0 ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit 0 ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit 0 ;; sun3*:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; mac68k:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; mvme68k:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; mvme88k:OpenBSD:*:*) echo m88k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit 0 ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit 0 ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit 0 ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit 0 ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit 0 ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD $dummy.c -o $dummy \ && ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \ && rm -f $dummy.c $dummy && exit 0 rm -f $dummy.c $dummy echo mips-mips-riscos${UNAME_RELEASE} exit 0 ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit 0 ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit 0 ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit 0 ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit 0 ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit 0 ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit 0 ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit 0 ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit 0 ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit 0 ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit 0 ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit 0 ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit 0 ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit 0 ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit 0 ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0 rm -f $dummy.c $dummy echo rs6000-ibm-aix3.2.5 elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit 0 ;; *:AIX:*:[45]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit 0 ;; *:AIX:*:*) echo rs6000-ibm-aix exit 0 ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit 0 ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit 0 ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit 0 ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit 0 ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit 0 ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit 0 ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) case "${HPUX_REV}" in 11.[0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; esac ;; esac fi ;; esac if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null ) && HP_ARCH=`./$dummy` if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi rm -f $dummy.c $dummy fi ;; esac echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit 0 ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit 0 ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0 rm -f $dummy.c $dummy echo unknown-hitachi-hiuxwe2 exit 0 ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit 0 ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit 0 ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit 0 ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit 0 ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit 0 ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit 0 ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit 0 ;; hppa*:OpenBSD:*:*) echo hppa-unknown-openbsd exit 0 ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit 0 ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit 0 ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit 0 ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit 0 ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit 0 ;; CRAY*X-MP:*:*:*) echo xmp-cray-unicos exit 0 ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit 0 ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit 0 ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit 0 ;; CRAY*T3D:*:*:*) echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit 0 ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit 0 ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit 0 ;; CRAY-2:*:*:*) echo cray2-cray-unicos exit 0 ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit 0 ;; hp300:OpenBSD:*:*) echo m68k-unknown-openbsd${UNAME_RELEASE} exit 0 ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit 0 ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit 0 ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit 0 ;; *:FreeBSD:*:*) echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit 0 ;; *:OpenBSD:*:*) echo ${UNAME_MACHINE}-unknown-openbsd`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` exit 0 ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit 0 ;; i*:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit 0 ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit 0 ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i386-pc-interix exit 0 ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit 0 ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit 0 ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit 0 ;; *:GNU:*:*) echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit 0 ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit 0 ;; arm*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit 0 ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux exit 0 ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit 0 ;; mips:Linux:*:*) case `sed -n '/^byte/s/^.*: \(.*\) endian/\1/p' < /proc/cpuinfo` in big) echo mips-unknown-linux-gnu && exit 0 ;; little) echo mipsel-unknown-linux-gnu && exit 0 ;; esac ;; ppc:Linux:*:*) echo powerpc-unknown-linux-gnu exit 0 ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-gnu exit 0 ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} exit 0 ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-gnu ;; PA8*) echo hppa2.0-unknown-linux-gnu ;; *) echo hppa-unknown-linux-gnu ;; esac exit 0 ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-gnu exit 0 ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux exit 0 ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit 0 ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-gnu exit 0 ;; x86_64:Linux:*:*) echo x86_64-unknown-linux-gnu exit 0 ;; i*86:Linux:*:*) # The BFD linker knows what the default object file format is, so # first see if it will tell us. cd to the root directory to prevent # problems with other programs or directories called `ld' in the path. ld_supported_targets=`cd /; ld --help 2>&1 \ | sed -ne '/supported targets:/!d s/[ ][ ]*/ /g s/.*supported targets: *// s/ .*// p'` case "$ld_supported_targets" in elf32-i386) TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" ;; a.out-i386-linux) echo "${UNAME_MACHINE}-pc-linux-gnuaout" exit 0 ;; coff-i386) echo "${UNAME_MACHINE}-pc-linux-gnucoff" exit 0 ;; "") # Either a pre-BFD a.out linker (linux-gnuoldld) or # one that does not give us useful --help. echo "${UNAME_MACHINE}-pc-linux-gnuoldld" exit 0 ;; esac # Determine whether the default compiler is a.out or elf eval $set_cc_for_build cat >$dummy.c < #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #ifdef __ELF__ # ifdef __GLIBC__ # if __GLIBC__ >= 2 printf ("%s-pc-linux-gnu\n", argv[1]); # else printf ("%s-pc-linux-gnulibc1\n", argv[1]); # endif # else printf ("%s-pc-linux-gnulibc1\n", argv[1]); # endif #else printf ("%s-pc-linux-gnuaout\n", argv[1]); #endif return 0; } EOF $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy "${UNAME_MACHINE}" && rm -f $dummy.c $dummy && exit 0 rm -f $dummy.c $dummy test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0 ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit 0 ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit 0 ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit 0 ;; i*86:*:5:[78]*) case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit 0 ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|egrep Release|sed -e 's/.*= //')` (/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit 0 ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit 0 ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i386. echo i386-pc-msdosdjgpp exit 0 ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit 0 ;; paragon:*:*:*) echo i860-intel-osf1 exit 0 ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit 0 ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit 0 ;; M68*:*:R3V[567]*:*) test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;; 3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 4850:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && echo i486-ncr-sysv4.3${OS_REL} && exit 0 /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && echo i486-ncr-sysv4 && exit 0 ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit 0 ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit 0 ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit 0 ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit 0 ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit 0 ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit 0 ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit 0 ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit 0 ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit 0 ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit 0 ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit 0 ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit 0 ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit 0 ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit 0 ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit 0 ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit 0 ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit 0 ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit 0 ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit 0 ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit 0 ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit 0 ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit 0 ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit 0 ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit 0 ;; *:Darwin:*:*) echo `uname -p`-apple-darwin${UNAME_RELEASE} exit 0 ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) if test "${UNAME_MACHINE}" = "x86pc"; then UNAME_MACHINE=pc fi echo `uname -p`-${UNAME_MACHINE}-nto-qnx exit 0 ;; *:QNX:*:4*) echo i386-pc-qnx exit 0 ;; NSR-[KW]:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit 0 ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit 0 ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit 0 ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit 0 ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit 0 ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit 0 ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit 0 ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit 0 ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit 0 ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit 0 ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit 0 ;; *:ITS:*:*) echo pdp10-unknown-its exit 0 ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit 0 ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit 0 ;; esac #echo '(No uname command or uname output not recognized.)' 1>&2 #echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 eval $set_cc_for_build cat >$dummy.c < # include #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (__arm) && defined (__acorn) && defined (__unix) printf ("arm-acorn-riscix"); exit (0); #endif #if defined (hp300) && !defined (hpux) printf ("m68k-hp-bsd\n"); exit (0); #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) # if !defined (ultrix) # include # if defined (BSD) # if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); # else # if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); # else printf ("vax-dec-bsd\n"); exit (0); # endif # endif # else printf ("vax-dec-bsd\n"); exit (0); # endif # else printf ("vax-dec-ultrix\n"); exit (0); # endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0 rm -f $dummy.c $dummy # Apollos put the system type in the environment. test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; } # Convex versions that predate uname can use getsysinfo(1) if [ -x /usr/convex/getsysinfo ] then case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd exit 0 ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit 0 ;; c34*) echo c34-convex-bsd exit 0 ;; c38*) echo c38-convex-bsd exit 0 ;; c4*) echo c4-convex-bsd exit 0 ;; esac fi cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: clearsilver-0.10.5/config.sub0000755001211700116100000006710010326267524013022 00000000000000#! /bin/sh # Configuration validation subroutine script. # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 # Free Software Foundation, Inc. timestamp='2001-09-07' # This file is (in principle) common to ALL GNU software. # The presence of a machine in this file suggests that SOME GNU software # can handle that machine. It does not imply ALL GNU software can. # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Please send patches to . # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit 0 ;; --version | -v ) echo "$version" ; exit 0 ;; --help | --h* | -h ) echo "$usage"; exit 0 ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit 0;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | storm-chaos* | os2-emx* | windows32-*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis) os= basic_machine=$1 ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \ | c4x | clipper \ | d10v | d30v | dsp16xx \ | fr30 \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | i370 | i860 | i960 | ia64 \ | m32r | m68000 | m68k | m88k | mcore \ | mips16 | mips64 | mips64el | mips64orion | mips64orionel \ | mips64vr4100 | mips64vr4100el | mips64vr4300 \ | mips64vr4300el | mips64vr5000 | mips64vr5000el \ | mipsbe | mipseb | mipsel | mipsle | mipstx39 | mipstx39el \ | mipsisa32 \ | mn10200 | mn10300 \ | ns16k | ns32k \ | openrisc \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ | pyramid \ | s390 | s390x \ | sh | sh[34] | sh[34]eb | shbe | shle \ | sparc | sparc64 | sparclet | sparclite | sparcv9 | sparcv9b \ | stormy16 | strongarm \ | tahoe | thumb | tic80 | tron \ | v850 \ | we32k \ | x86 | xscale \ | z8k) basic_machine=$basic_machine-unknown ;; m6811 | m68hc11 | m6812 | m68hc12) # Motorola 68HC11/12. basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alphapca5[67]-* | arc-* \ | arm-* | armbe-* | armle-* | armv*-* \ | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c54x-* \ | clipper-* | cray2-* | cydra-* \ | d10v-* | d30v-* \ | elxsi-* \ | f30[01]-* | f700-* | fr30-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | i*86-* | i860-* | i960-* | ia64-* \ | m32r-* \ | m68000-* | m680[01234]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | mcore-* \ | mips-* | mips16-* | mips64-* | mips64el-* | mips64orion-* \ | mips64orionel-* | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* | mipsbe-* | mipseb-* \ | mipsle-* | mipsel-* | mipstx39-* | mipstx39el-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ | pyramid-* \ | romp-* | rs6000-* \ | s390-* | s390x-* \ | sh-* | sh[34]-* | sh[34]eb-* | shbe-* | shle-* \ | sparc-* | sparc64-* | sparc86x-* | sparclite-* \ | sparcv9-* | sparcv9b-* | stormy16-* | strongarm-* | sv1-* \ | t3e-* | tahoe-* | thumb-* | tic30-* | tic54x-* | tic80-* | tron-* \ | v850-* | vax-* \ | we32k-* \ | x86-* | x86_64-* | xmp-* | xps100-* | xscale-* \ | ymp-* \ | z8k-*) ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | ymp) basic_machine=ymp-cray os=-unicos ;; cray2) basic_machine=cray2-cray os=-unicos ;; [cjt]90) basic_machine=${basic_machine}-cray os=-unicos ;; crds | unos) basic_machine=m68k-crds ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; # I'm not sure what "Sysv32" means. Should this be sysv3.2? i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; mingw32) basic_machine=i386-pc os=-mingw32 ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mipsel*-linux*) basic_machine=mipsel-unknown os=-linux-gnu ;; mips*-linux*) basic_machine=mips-unknown os=-linux-gnu ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; mmix*) basic_machine=mmix-knuth os=-mmixware ;; monitor) basic_machine=m68k-rom68k os=-coff ;; msdos) basic_machine=i386-pc os=-msdos ;; mvs) basic_machine=i370-ibm os=-mvs ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pentium | p5 | k5 | k6 | nexgen) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon) basic_machine=i686-pc ;; pentiumii | pentium2) basic_machine=i686-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc) basic_machine=powerpc-unknown ;; ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sparclite-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=t3e-cray os=-unicos ;; tic54x | c54x*) basic_machine=tic54x-unknown os=-coff ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; tower | tower-32) basic_machine=m68k-ncr ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; windows32) basic_machine=i386-pc os=-windows32-msvcrt ;; xmp) basic_machine=xmp-cray os=-unicos ;; xps | xps100) basic_machine=xps100-honeywell ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; mips) if [ x$os = x-linux-gnu ]; then basic_machine=mips-unknown else basic_machine=mips-mips fi ;; romp) basic_machine=romp-ibm ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh3 | sh4 | sh3eb | sh4eb) basic_machine=sh-unknown ;; sparc | sparcv9 | sparcv9b) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; c4x*) basic_machine=c4x-none os=-coff ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \ | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* \ | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto*) os=-nto-qnx ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 # This also exists in the configure program, but was not the # default. # os=-sunos4 ;; m68*-cisco) os=-aout ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-ibm) os=-aix ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -ptx*) vendor=sequent ;; -vxsim* | -vxworks*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit 0 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: clearsilver-0.10.5/configure.in0000644001211700116100000003515010645501211013334 00000000000000dnl Process this file with autoconf to produce a configure script. AC_INIT(cgi/cgi.c) AC_CONFIG_HEADER(cs_config.h) dnl Checks for programs. AC_PROG_CC AC_PROG_CPP AC_PROG_LN_S AC_CHECK_PROGS(AR, ar aal, ar) AC_PROG_RANLIB AC_PROG_MAKE_SET AC_PROG_INSTALL dnl Checks for Neotonic Paths AC_MSG_CHECKING(for Neotonic Paths) if test -d /neo/opt/include; then AC_MSG_RESULT(found) CPPFLAGS="$CPPFLAGS -I/neo/opt/include" LDFLAGS="$LDFLAGS -L/neo/opt/lib" else AC_MSG_RESULT(not found) fi dnl Checks for header files. AC_HEADER_DIRENT AC_HEADER_STDC AC_HEADER_SYS_WAIT AC_CHECK_HEADERS(fcntl.h stdarg.h varargs.h limits.h strings.h sys/ioctl.h sys/time.h unistd.h features.h) dnl Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_MODE_T AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T AC_HEADER_TIME AC_STRUCT_TM AC_STRUCT_TIMEZONE dnl Checks for library functions. AC_TYPE_SIGNAL AC_FUNC_STRFTIME AC_FUNC_VPRINTF AC_FUNC_WAIT3 AC_CHECK_FUNCS(gettimeofday mktime putenv strerror strspn strtod strtol strtoul) AC_CHECK_FUNCS(random rand drand48) dnl Checks for libraries. EXTRA_UTL_OBJS= EXTRA_UTL_SRC= cs_cv_wdb=no AC_ARG_ENABLE(apache, [ --disable-wdb Disables building of wdb], [if test $enableval = no; then AC_MSG_RESULT(Disabling wdb code) else AC_SEARCH_LIBS(db_open, db db2, [cs_cv_wdb=yes]) if test $cs_cv_wdb = yes; then AC_DEFINE(HAVE_DB2) EXTRA_UTL_SRC="$EXTRA_UTL_SRC wdb.c" fi fi]) dnl Check for locks AC_CHECK_FUNC(lockf, [ AC_DEFINE(HAVE_LOCKF) EXTRA_UTL_SRC="$EXTRA_UTL_SRC ulocks.c rcfs.c" cs_cv_pthread=no AC_CHECK_HEADER(pthread.h, [cs_cv_pthread=yes]) if test $cs_cv_pthread = yes; then AC_DEFINE(HAVE_PTHREADS) EXTRA_UTL_SRC="$EXTRA_UTL_SRC skiplist.c dict.c" fi ]) AC_MINGW32() if test "x$MINGW32" = "xyes"; then CPPFLAGS="$CPPFLAGS -D__WINDOWS_GCC__" USE_MINGW32="USE_MINGW32 = 1" else EXTRA_UTL_SRC="$EXTRA_UTL_SRC filter.c neo_net.c neo_server.c" fi dnl Check for snprintf and vsnprintf cs_cv_snprintf=no SNPRINTFOBJS="" AC_CHECK_FUNC(snprintf, [AC_DEFINE(HAVE_SNPRINTF)], [cs_cv_snprintf=yes]) AC_CHECK_FUNC(vsnprintf, [AC_DEFINE(HAVE_VSNPRINTF)], [cs_cv_snprintf=yes]) if test $cs_cv_snprintf = yes; then EXTRA_UTL_OBJS="$EXTRA_UTL_OBJS snprintf.o" fi dnl Check for missing re-entrant functions cs_cv_missing=no cs_cv_need_reentrant=no dnl copied from libcurl AC_CHECK_FUNCS(localtime_r, [ AC_MSG_CHECKING(whether localtime_r is declared) AC_EGREP_CPP(localtime_r,[ #include ],[ AC_DEFINE(HAVE_LOCALTIME_R) AC_MSG_RESULT(yes)],[ AC_MSG_RESULT(no) AC_MSG_CHECKING(whether localtime_r with -D_REENTRANT is declared) AC_EGREP_CPP(localtime_r,[ #define _REENTRANT #include ],[ cs_cv_need_reentrant=yes AC_MSG_RESULT(yes)],[ cs_cv_missing=yes AC_MSG_RESULT(no)])])], [cs_cv_missing=yes]) AC_CHECK_FUNCS(gmtime_r, [ AC_MSG_CHECKING(whether gmtime_r is declared) AC_EGREP_CPP(gmtime_r,[ #include ],[ AC_DEFINE(HAVE_GMTIME_R) AC_MSG_RESULT(yes)],[ AC_MSG_RESULT(no) AC_MSG_CHECKING(whether gmtime_r with -D_REENTRANT is declared) AC_EGREP_CPP(gmtime_r,[ #define _REENTRANT #include ],[ cs_cv_need_reentrant=yes AC_MSG_RESULT(yes)],[ cs_cv_missing=yes AC_MSG_RESULT(no)])])], [cs_cv_missing=yes]) AC_CHECK_FUNCS(strtok_r, [ AC_MSG_CHECKING(whether strtok_r is declared) AC_EGREP_CPP(strtok_r,[ #include ],[ AC_DEFINE(HAVE_STRTOK_R) AC_MSG_RESULT(yes)],[ AC_MSG_RESULT(no) AC_MSG_CHECKING(whether strtok_r with -D_REENTRANT is declared) AC_EGREP_CPP(strtok_r,[ #define _REENTRANT #include ],[ cs_cv_need_reentrant=yes AC_MSG_RESULT(yes)],[ cs_cv_missing=yes AC_MSG_RESULT(no)])])], [cs_cv_missing=yes]) AC_CHECK_FUNC(mkstemp, [AC_DEFINE(HAVE_MKSTEMP)], [cs_cv_missing=yes]) if test $cs_cv_missing = yes; then EXTRA_UTL_OBJS="$EXTRA_UTL_OBJS missing.o" fi if test $cs_cv_need_reentrant = yes; then CPPFLAGS="$CPPFLAGS -D_REENTRANT" fi cs_cv_regex=yes AC_CHECK_FUNC(regexec, [AC_DEFINE(HAVE_REGEX)], [cs_cv_regex=no]) if test $cs_cv_regex = no; then CPPFLAGS="$CPPFLAGS -I\$(NEOTONIC_ROOT)/util/regex" EXTRA_UTL_SRC="$EXTRA_UTL_SRC regex/regex.c" fi cs_cv_compression=yes AC_CHECK_LIB(z, deflate, [cs_cv_compression=yes], [cs_cv_compression=no]) AC_ARG_ENABLE(compression, [ --disable-compression Disables HTML Compression support], [if test $enableval = no; then cs_cv_compression=no; AC_MSG_RESULT(Disabling HTML Compression support) fi]) if test $cs_cv_compression = yes; then AC_DEFINE(HTML_COMPRESSION) LIBS="$LIBS -lz" fi AC_ARG_ENABLE(remote-debugger, [ --enable-remote-debugger Enables remote X CGI debugging], [if test $enableval = yes; then AC_DEFINE(ENABLE_REMOTE_DEBUG) AC_MSG_RESULT(Enabling CGI X Remote debugger) fi]) dnl Check for Apache apxs cs_cv_apache=yes AC_ARG_ENABLE(apache, [ --disable-apache Disables building of apache 1.3.x module], [if test $enableval = no; then cs_cv_apache=no; AC_MSG_RESULT(Disabling Apache 1.3.x Module) fi]) AC_ARG_WITH(apache, [ --with-apache=path Set location of Apache installation], [cs_cv_apache_path="$withval"], [cs_cv_apache_path=]) if test $cs_cv_apache = yes; then AC_MSG_CHECKING(for apache apxs) apxs_path=no apache_search_path="$cs_cv_apache_path /neo/opt /usr/local /usr" for path in $apache_search_path; do if test -x $path/httpd/bin/apxs; then apxs_path=$path/httpd/bin/apxs httpd_path=$path/httpd/bin/httpd break fi if test -x $path/httpd/sbin/apxs; then apxs_path=$path/httpd/sbin/apxs httpd_path=$path/httpd/sbin/httpd break fi if test -x $path/bin/apxs; then apxs_path=$path/bin/apxs httpd_path=$path/bin/httpd break fi if test -x $path/sbin/apxs; then apxs_path=$path/sbin/apxs httpd_path=$path/sbin/httpd break fi done if test "x$apxs_path" = "xno"; then AC_MSG_RESULT(not found) else AC_MSG_RESULT(found $apxs_path) AC_MSG_CHECKING(for apache 1.3.x) changequote(<<, >>)dnl apache_version="`$httpd_path -v | grep 'Server version' | sed -e 's/.*Apache\/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/'`" apache_major_version=`echo $apache_version | sed -e 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'` apache_minor_version=`echo $apache_version | sed -e 's/.*\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'` changequote([, ])dnl if test "$apache_major_version" = "1" -a "$apache_minor_version" = "3"; then AC_MSG_RESULT(found $apache_version) APXS_PATH="$apxs_path" BUILD_WRAPPERS="$BUILD_WRAPPERS mod_ecs" else AC_MSG_RESULT(found $apache_version - disabling module build) fi fi fi dnl Check for Python library/includes cs_cv_python=yes AC_ARG_ENABLE(python, [ --disable-python Disables building of python module], [if test $enableval = no; then cs_cv_python=no; AC_MSG_RESULT(Disabling python module) fi]) AC_ARG_WITH(python, [ --with-python=path Set location of Python Interpreter], [cs_cv_python_path="$withval"], [cs_cv_python_path=no]) if test $cs_cv_python = yes; then AC_MSG_CHECKING(for python includes) python_inc=no python_lib=no python_search_path="/neo/opt /usr/local /usr /c" python_versions="2.4 2.3 2.2 2.1 2.0 1.5 24 23 22 21 20 15" if test $cs_cv_python_path != "no" -a -x $cs_cv_python_path; then python_bin=$cs_cv_python_path vers=`$python_bin -c "import sys; print sys.version[[:3]]"` py_inst_dir=`$python_bin -c "import sys; print sys.exec_prefix"` python_inc=$py_inst_dir/include/python$vers python_lib="-L$py_inst_dir/lib/python$vers/config -lpython$vers" python_site=$py_inst_dir/lib/python$vers/site-packages else for vers in $python_versions; do for path in $python_search_path; do if test -x $path/bin/python$vers; then python_bin=$path/bin/python$vers major_vers=`echo $vers | cut -b 1` if test $major_vers -ge 2; then python_base=`$python_bin -c "import sys, os; print os.path.dirname([[x for x in sys.path if x.find('site-packages') != -1]][[0]])"` else python_base=`$python_bin -c "import site, os; print os.path.dirname(site.sitedirs[[0]])"` fi if test -d $python_base; then python_lib="-L$python_base/config -lpython$vers" python_site=$python_base/site-packages fi fi if test -f $path/include/python$vers/Python.h; then python_inc=$path/include/python$vers fi if test "x$python_lib" = "xno"; then if test -d $path/lib/python$vers; then python_lib="-L$path/lib/python$vers/config -lpython$vers" python_site=$path/lib/python$vers/site-packages fi if test -d $path/lib64/python$vers; then python_lib="-L$path/lib64/python$vers/config -lpython$vers" python_site=$path/lib64/python$vers/site-packages fi fi dnl This is currently special cased mostly for Windows dnl installs, but we only use python_lib for windows anyways if test -f $path/python$vers/include/Python.h; then python_inc=$path/python$vers/include python_lib="-L$path/python$vers/libs -lpython$vers" python_site=$path/python$vers/Lib/site-packages break 2 fi if test "x$python_inc" != "xno" -a "x$python_lib" != "xno"; then break 2 fi done done fi if test "x$python_inc" = "xno"; then AC_MSG_RESULT(not found) PYTHON= PYTHON_INC= PYTHON_LIB= PYTHON_SITE= else AC_MSG_RESULT(found $python_inc) PYTHON=$python_bin PYTHON_INC="-I$python_inc" PYTHON_LIB=$python_lib if test "x$PYTHON_SITE" = "x"; then PYTHON_SITE=$python_site fi BUILD_WRAPPERS="$BUILD_WRAPPERS python" fi fi dnl Check for Perl binary cs_cv_perl=yes AC_ARG_ENABLE(perl, [ --disable-perl Disables building of perl module], [if test $enableval = no; then cs_cv_perl=no; AC_MSG_RESULT(Disabling perl module) fi]) AC_ARG_WITH(perl, [ --with-perl=path Set location of Perl binary], [cs_cv_perl_path="$withval"], [cs_cv_perl_path=no]) if test $cs_cv_perl = yes; then AC_MSG_CHECKING(for perl >= 5.006) perl_path=no perl_search_path="/neo/opt /usr/local /usr" if test $cs_cv_perl_path != "no" -a -x $cs_cv_perl_path; then perl_path=$cs_cv_perl_path else for path in $perl_search_path; do if test -x $path/bin/perl; then require_error=`$path/bin/perl -e 'require 5.006' 2>&1` if test "x$require_error" = "x"; then perl_path=$path/bin/perl break fi fi done fi if test "x$perl_path" = "xno"; then AC_MSG_RESULT(not found) PERL= else AC_MSG_RESULT(found $perl_path) PERL="$perl_path" BUILD_WRAPPERS="$BUILD_WRAPPERS perl" fi fi dnl Check for Ruby binary cs_cv_ruby=yes AC_ARG_ENABLE(ruby, [ --disable-ruby Disables building of ruby module], [if test $enableval = no; then cs_cv_ruby=no; AC_MSG_RESULT(Disabling ruby module) fi]) AC_ARG_WITH(ruby, [ --with-ruby=path Set location of Ruby binary], [cs_cv_ruby_path="$withval"], [cs_cv_ruby_path=no]) if test $cs_cv_ruby = yes; then AC_MSG_CHECKING(for ruby) ruby_path=no ruby_search_path="/neo/opt /usr/local /usr" if test $cs_cv_ruby_path != "no" -a -x $cs_cv_ruby_path; then ruby_path=$cs_cv_ruby_path else for path in $ruby_search_path; do if test -x $path/bin/ruby; then ruby_path=$path/bin/ruby break fi done fi if test "x$ruby_path" = "xno"; then AC_MSG_RESULT(not found) RUBY= else AC_MSG_RESULT(found $ruby_path) RUBY="$ruby_path" BUILD_WRAPPERS="$BUILD_WRAPPERS ruby" fi fi dnl Check for Java library/includes cs_cv_java=yes AC_ARG_ENABLE(java, [ --disable-java Disables building of java module], [if test $enableval = no; then cs_cv_java=no; AC_MSG_RESULT(Disabling java module) fi]) AC_ARG_WITH(java, [ --with-java=path Set location of J2SDK], [cs_cv_java_path="$withval"], [cs_cv_java_path=no]) if test $cs_cv_java = yes; then AC_MSG_CHECKING(for j2sdk path) java_path=no if test $cs_cv_java_path != "no" -a -d $cs_cv_java_path; then java_path=$cs_cv_java_path else java_search_path="/neo/opt /usr/local /usr /usr/lib" for path in $java_search_path; do if test -d $path/java/j2sdk; then java_path=$path/java/j2sdk break fi if test -d $path/j2sdk; then java_path=$path/j2sdk break fi possible="$path/java/j2sdk*" for pos_path in $possible; do if test -d $pos_path; then java_path=$pos_path break 2 fi done possible="$path/j2sdk*" for pos_path in $possible; do if test -d $pos_path; then java_path=$pos_path break 2 fi done done fi if test "x$java_path" = "xno"; then AC_MSG_RESULT(not found) JAVA_PATH= JAVA_INCLUDE_PATH= else AC_MSG_RESULT(found $java_path) JAVA_PATH="$java_path" JAVAC="$java_path/bin/javac" _ACJNI_JAVAC=$JAVAC AC_JNI_INCLUDE_DIR for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS do JAVA_INCLUDE_PATH="$JAVA_INCLUDE_PATH -I$JNI_INCLUDE_DIR" done BUILD_WRAPPERS="$BUILD_WRAPPERS java-jni" fi fi dnl Check for C# library/includes cs_cv_csharp=yes AC_ARG_ENABLE(csharp, [ --disable-csharp Disables building of csharp module], [if test $enableval = no; then cs_cv_csharp=no; AC_MSG_RESULT(Disabling csharp module) fi]) AC_ARG_WITH(csharp, [ --with-csharp=path Set location of csharp], [cs_cv_csharp_path="$withval"], [cs_cv_csharp_path=no]) if test $cs_cv_csharp = yes; then AC_MSG_CHECKING(for csharp path) csharp_path=no if test $cs_cv_csharp_path != "no" -a -d $cs_cv_csharp_path; then csharp_path=$cs_cv_csharp_path else csharp_search_path="/neo/opt /usr/local /usr" for path in $csharp_search_path; do if test -f $path/bin/mcs; then csharp_path=$path break fi done fi if test "x$csharp_path" = "xno"; then AC_MSG_RESULT(not found) CSHARP_PATH= else AC_MSG_RESULT(found $csharp_path/bin/mcs) CSHARP_PATH="$csharp_path" BUILD_WRAPPERS="$BUILD_WRAPPERS dso csharp" fi fi AC_ARG_ENABLE(gettext, [ --enable-gettext Enables gettext message translation], [if test $enableval = yes; then dnl Check for gettext AC_CHECK_FUNC(gettext, [ cs_cv_libintl=no AC_CHECK_HEADER(libintl.h, [cs_cv_libintl=yes]) if test $cs_cv_libintl = yes; then AC_DEFINE(ENABLE_GETTEXT) AC_MSG_RESULT(Enabling gettext message translation) else AC_MSG_RESULT(not found) fi ]) fi]) AC_SUBST(RANLIB) AC_SUBST(AR) AC_SUBST(USE_MINGW32) AC_SUBST(APXS_PATH) AC_SUBST(PERL) AC_SUBST(RUBY) AC_SUBST(BUILD_WRAPPERS) AC_SUBST(JAVA_PATH) AC_SUBST(JAVA_INCLUDE_PATH) AC_SUBST(PYTHON) AC_SUBST(PYTHON_INC) AC_SUBST(PYTHON_LIB) AC_SUBST(PYTHON_SITE) AC_SUBST(EXTRA_UTL_SRC) AC_SUBST(EXTRA_UTL_OBJS) AC_SUBST(CSHARP_PATH) AC_OUTPUT(rules.mk) clearsilver-0.10.5/cs_config.h.in0000644001211700116100000001401510540411115013525 00000000000000/* cs_config.h.in. Generated from configure.in by autoheader. */ /* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * config file */ #ifndef __CS_CONFIG_H_ #define __CS_CONFIG_H_ 1 /* Enable support for HTML Compression (still must be enabled at run time) */ #undef HTML_COMPRESSION /* Enable support for X Remote CGI Debugging */ #undef ENABLE_REMOTE_DEBUG /********* SYSTEM CONFIG ***************************************************/ /* autoconf/configure should figure all of these out for you */ /* Does your system have the snprintf() call? */ #undef HAVE_SNPRINTF /* Does your system have the vsnprintf() call? */ #undef HAVE_VSNPRINTF /* Does your system have the strtok_r() call? */ #undef HAVE_STRTOK_R /* Does your system have the localtime_r() call? */ #undef HAVE_LOCALTIME_R /* Does your system have the gmtime_r() call? */ #undef HAVE_GMTIME_R /* Does your system have the mkstemp() call? */ #undef HAVE_MKSTEMP /* Does your system have regex.h */ #undef HAVE_REGEX /* Does your system have pthreads? */ #undef HAVE_PTHREADS /* Does your system have lockf ? */ #undef HAVE_LOCKF /* Does your system have Berkeley DB v2 ? */ #undef HAVE_DB2 /* Enable support for gettext message translation */ #undef ENABLE_GETTEXT /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_DIRENT_H /* Define to 1 if you don't have `vprintf' but do have `_doprnt.' */ #undef HAVE_DOPRNT /* Define to 1 if you have the `drand48' function. */ #undef HAVE_DRAND48 /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define to 1 if you have the header file. */ #undef HAVE_FEATURES_H /* Define to 1 if you have the `gettimeofday' function. */ #undef HAVE_GETTIMEOFDAY /* Define to 1 if you have the `gmtime_r' function. */ #undef HAVE_GMTIME_R /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_LIMITS_H /* Define to 1 if you have the `localtime_r' function. */ #undef HAVE_LOCALTIME_R /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the `mktime' function. */ #undef HAVE_MKTIME /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_NDIR_H /* Define to 1 if you have the `putenv' function. */ #undef HAVE_PUTENV /* Define to 1 if you have the `rand' function. */ #undef HAVE_RAND /* Define to 1 if you have the `random' function. */ #undef HAVE_RANDOM /* Define to 1 if you have the header file. */ #undef HAVE_STDARG_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the `strerror' function. */ #undef HAVE_STRERROR /* Define to 1 if you have the `strftime' function. */ #undef HAVE_STRFTIME /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the `strspn' function. */ #undef HAVE_STRSPN /* Define to 1 if you have the `strtod' function. */ #undef HAVE_STRTOD /* Define to 1 if you have the `strtok_r' function. */ #undef HAVE_STRTOK_R /* Define to 1 if you have the `strtol' function. */ #undef HAVE_STRTOL /* Define to 1 if you have the `strtoul' function. */ #undef HAVE_STRTOUL /* Define to 1 if `tm_zone' is member of `struct tm'. */ #undef HAVE_STRUCT_TM_TM_ZONE /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_DIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_IOCTL_H /* Define to 1 if you have the header file, and it defines `DIR'. */ #undef HAVE_SYS_NDIR_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TIME_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have that is POSIX.1 compatible. */ #undef HAVE_SYS_WAIT_H /* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use `HAVE_STRUCT_TM_TM_ZONE' instead. */ #undef HAVE_TM_ZONE /* Define to 1 if you don't have `tm_zone' but do have the external array `tzname'. */ #undef HAVE_TZNAME /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the header file. */ #undef HAVE_VARARGS_H /* Define to 1 if you have the `vprintf' function. */ #undef HAVE_VPRINTF /* Define to 1 if you have the `wait3' system call. Deprecated, you should no longer depend upon `wait3'. */ #undef HAVE_WAIT3 /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Define as the return type of signal handlers (`int' or `void'). */ #undef RETSIGTYPE /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define to 1 if you can safely include both and . */ #undef TIME_WITH_SYS_TIME /* Define to 1 if your declares `struct tm'. */ #undef TM_IN_SYS_TIME /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `int' if does not define. */ #undef mode_t /* Define to `long' if does not define. */ #undef off_t /* Define to `int' if does not define. */ #undef pid_t /* Define to `unsigned' if does not define. */ #undef size_t #endif /* __CS_CONFIG_H_ */ clearsilver-0.10.5/mkinstalldirs0000755001211700116100000000133010261037512013624 00000000000000#! /bin/sh # mkinstalldirs --- make directory hierarchy # Author: Noah Friedman # Created: 1993-05-16 # Public domain # $Id: mkinstalldirs,v 1.1 2003/04/02 23:07:26 blong Exp $ errstatus=0 for file do set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'` shift pathcomp= for d do pathcomp="$pathcomp$d" case "$pathcomp" in -* ) pathcomp=./$pathcomp ;; esac if test ! -d "$pathcomp"; then echo "mkdir $pathcomp" 1>&2 mkdir "$pathcomp" || lasterr=$? if test ! -d "$pathcomp"; then errstatus=$lasterr fi fi pathcomp="$pathcomp/" done done exit $errstatus # mkinstalldirs ends here clearsilver-0.10.5/install-sh0000755001211700116100000001124410261037512013027 00000000000000#! /bin/sh # # install - install a program, script, or datafile # This comes from X11R5. # # Calling this script install-sh is preferred over install.sh, to prevent # `make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. # # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit="${DOITPROG-}" # put in absolute paths if you don't have them in your path; or use env. vars. mvprog="${MVPROG-mv}" cpprog="${CPPROG-cp}" chmodprog="${CHMODPROG-chmod}" chownprog="${CHOWNPROG-chown}" chgrpprog="${CHGRPPROG-chgrp}" stripprog="${STRIPPROG-strip}" rmprog="${RMPROG-rm}" mkdirprog="${MKDIRPROG-mkdir}" tranformbasename="" transform_arg="" instcmd="$mvprog" chmodcmd="$chmodprog 0755" chowncmd="" chgrpcmd="" stripcmd="" rmcmd="$rmprog -f" mvcmd="$mvprog" src="" dst="" dir_arg="" while [ x"$1" != x ]; do case $1 in -c) instcmd="$cpprog" shift continue;; -d) dir_arg=true shift continue;; -m) chmodcmd="$chmodprog $2" shift shift continue;; -o) chowncmd="$chownprog $2" shift shift continue;; -g) chgrpcmd="$chgrpprog $2" shift shift continue;; -s) stripcmd="$stripprog" shift continue;; -t=*) transformarg=`echo $1 | sed 's/-t=//'` shift continue;; -b=*) transformbasename=`echo $1 | sed 's/-b=//'` shift continue;; *) if [ x"$src" = x ] then src=$1 else # this colon is to work around a 386BSD /bin/sh bug : dst=$1 fi shift continue;; esac done if [ x"$src" = x ] then echo "install: no input file specified" exit 1 else true fi if [ x"$dir_arg" != x ]; then dst=$src src="" if [ -d $dst ]; then instcmd=: else instcmd=mkdir fi else # Waiting for this to be detected by the "$instcmd $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if [ -f $src -o -d $src ] then true else echo "install: $src does not exist" exit 1 fi if [ x"$dst" = x ] then echo "install: no destination specified" exit 1 else true fi # If destination is a directory, append the input filename; if your system # does not like double slashes in filenames, you may need to add some logic if [ -d $dst ] then dst="$dst"/`basename $src` else true fi fi ## this sed command emulates the dirname command dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'` # Make sure that the destination directory exists. # this part is taken from Noah Friedman's mkinstalldirs script # Skip lots of stat calls in the usual case. if [ ! -d "$dstdir" ]; then defaultIFS=' ' IFS="${IFS-${defaultIFS}}" oIFS="${IFS}" # Some sh's can't handle IFS=/ for some reason. IFS='%' set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'` IFS="${oIFS}" pathcomp='' while [ $# -ne 0 ] ; do pathcomp="${pathcomp}${1}" shift if [ ! -d "${pathcomp}" ] ; then $mkdirprog "${pathcomp}" else true fi pathcomp="${pathcomp}/" done fi if [ x"$dir_arg" != x ] then $doit $instcmd $dst && if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi else # If we're going to rename the final executable, determine the name now. if [ x"$transformarg" = x ] then dstfile=`basename $dst` else dstfile=`basename $dst $transformbasename | sed $transformarg`$transformbasename fi # don't allow the sed command to completely eliminate the filename if [ x"$dstfile" = x ] then dstfile=`basename $dst` else true fi # Make a temp file name in the proper directory. dsttmp=$dstdir/#inst.$$# # Move or copy the file name to the temp name $doit $instcmd $src $dsttmp && trap "rm -f ${dsttmp}" 0 && # and set any options; do chmod last to preserve setuid bits # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $instcmd $src $dsttmp" command. if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi && if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi && if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi && if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi && # Now rename the file to the real destination. $doit $rmcmd -f $dstdir/$dstfile && $doit $mvcmd $dsttmp $dstdir/$dstfile fi && exit 0 clearsilver-0.10.5/ClearSilver.h0000644001211700116100000000335310261037503013411 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __CLEARSILVER_H_ #define __CLEARSILVER_H_ 1 #include "cs_config.h" /* If you need these backward compatible definitions, define CS_COMPAT */ /* These changed after v0.9.1 */ #define CS_COMPAT 0 #if defined(CS_COMPAT) || !defined(HASH) #define HASH NE_HASH #define HASHNODE NE_HASHNODE #define hash_init ne_hash_init #define hash_destroy ne_hash_destroy #define hash_lookup ne_hash_lookup #define hash_has_key ne_hash_has_key #define hash_remove ne_hash_remove #define hash_next ne_hash_next #define hash_str_comp ne_hash_str_comp #define hash_str_hash ne_hash_str_hash #endif /* CS_COMPAT */ #include #include /* Base libraries */ #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_date.h" #include "util/neo_files.h" #include "util/neo_hash.h" #include "util/neo_hdf.h" #include "util/neo_rand.h" #include "util/neo_net.h" #include "util/neo_server.h" #include "util/neo_str.h" #include "util/ulist.h" #include "util/wildmat.h" #include "util/filter.h" #ifdef HAVE_LOCKF # include "util/ulocks.h" # include "util/rcfs.h" /* These are dependent on the pthread locking code in ulocks */ # ifdef HAVE_PTHREADS # include "util/skiplist.h" # include "util/dict.h" # endif #endif /* This is dependent on Berkeley DB v2 */ #ifdef HAVE_DB2 # include "util/wdb.h" #endif /* The ClearSilver Template language */ #include "cs/cs.h" /* The ClearSilver CGI connector */ #include "cgi/cgi.h" #include "cgi/cgiwrap.h" #include "cgi/date.h" #include "cgi/html.h" #endif /* __CLEARSILVER_H_ */ clearsilver-0.10.5/util/0000755001211700116100000000000010645505044012064 500000000000000clearsilver-0.10.5/util/Makefile0000644001211700116100000000126410344021620013434 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk UTL_LIB = $(LIB_DIR)libneo_utl.a UTL_SRC = neo_err.c neo_files.c neo_misc.c neo_rand.c ulist.c neo_hdf.c \ neo_str.c neo_date.c wildmat.c neo_hash.c $(EXTRA_UTL_SRC) UTL_OBJ = $(UTL_SRC:%.c=%.o) $(EXTRA_UTL_OBJS) UTL_HDR = $(UTL_SRC:%.c=%.h) TARGETS = $(UTL_LIB) all: $(TARGETS) $(UTL_LIB): $(UTL_OBJ) $(AR) $@ $(UTL_OBJ) $(RANLIB) $@ install: all $(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(cs_includedir)/util $(INSTALL) -m 644 $(UTL_HDR) $(DESTDIR)$(cs_includedir)/util $(INSTALL) -m 644 $(UTL_LIB) $(DESTDIR)$(libdir) clean: $(RM) *.o distclean: $(RM) Makefile.depends $(TARGETS) *.o clearsilver-0.10.5/util/dict.c0000644001211700116100000003166610261111332013072 00000000000000/* * * Thread-safe Dictionary Using String Identifiers * Copyright 1998-2000 Scott Shambarger (scott@shambarger.net) * * This software is open source. Permission to use, copy, modify, and * distribute this software for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies. No * warranty of any kind is expressed or implied. Use at your own risk. * */ #include "cs_config.h" #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "dict.h" #include "skiplist.h" #include "ulocks.h" typedef struct dictValue { void *value; /* value to set/update */ dictNewValueCB new; /* new value callback (value is NULL) */ dictUpdateValueCB update; /* update value callback (value is NULL) */ void *rock; /* rock to pass to callbacks */ } *dictValuePtr; typedef struct dictItem { struct dictItem *next; /* pointer to next value */ char *id; /* string id */ void *value; /* value */ } *dictItemPtr; typedef struct dictEntry { dictItemPtr first; /* first item in entry */ BOOL deleted; /* TRUE if entry has been passed to skipDelete */ } *dictEntryPtr; typedef UINT32 (*dictHashFunc)(const char *str); typedef int (*dictCompFunc)(const char *s1, const char *s2); struct _dictCtx { pthread_mutex_t mList; /* list update mutex */ skipList list; /* skip list */ dictHashFunc hash; /* hash function */ dictCompFunc comp; /* id compare function */ BOOL useCase; BOOL threaded; /* TRUE if threaded */ dictFreeValueFunc freeValue; /* free value callback */ void *freeRock; /* context for freeValue */ }; #undef DO_DEBUG #ifdef DO_DEBUG #include #define DICT_LOCK(dict) \ do { if((dict)->threaded) { sched_yield(); \ mLock(&(dict)->mList); } } while(0) #define DICT_HASH_BITS 16 #else #define DICT_LOCK(dict) \ if((dict)->threaded) mLock(&(dict)->mList) #define DICT_HASH_BITS 65536 #endif #define DICT_UNLOCK(dict) \ if((dict)->threaded) mUnlock(&(dict)->mList) /* entry is locked, so item may be added */ static NEOERR *dictNewItem(dictCtx dict, dictEntryPtr entry, const char *id, dictValuePtr newval, dictItemPtr *item) { dictItemPtr my_item; if (item != NULL) *item = NULL; /* check if we can set a new value */ if(! (newval->value || newval->new)) return nerr_raise(NERR_ASSERT, "value or new are NULL"); if(! (my_item = calloc(1, sizeof(struct dictItem)))) return nerr_raise(NERR_NOMEM, "Unable to allocate new dictItem"); if(! (my_item->id = strdup(id))) { free(my_item); return nerr_raise(NERR_NOMEM, "Unable to allocate new id for dictItem"); } /* set new value */ if(newval->value) { my_item->value = newval->value; } else { NEOERR *err = STATUS_OK; err = newval->new(id, newval->rock, &(my_item->value)); if (err != STATUS_OK) { /* new item callback failed, cleanup */ free(my_item->id); free(my_item); return nerr_pass(err); } } my_item->next = entry->first; entry->first = my_item; if (item != NULL) *item = my_item; return STATUS_OK; } static void dictFreeItem(dictCtx dict, dictItemPtr item) { if(dict->freeValue) dict->freeValue(item->value, dict->freeRock); free(item->id); free(item); return; } /* list locked, so safe to walk entry */ static dictItemPtr dictFindItem(dictCtx dict, dictEntryPtr entry, const char *id, BOOL unlink) { dictItemPtr *prev, item; prev = &entry->first; for(item = entry->first; item; item = item->next) { if(! dict->comp(item->id, id)) { if(unlink) *prev = item->next; return item; } prev = &item->next; } return NULL; } static NEOERR *dictUpdate(dictCtx dict, dictEntryPtr entry, const char *id, dictValuePtr newval, void *lock) { NEOERR *err = STATUS_OK; dictItemPtr item = NULL; void *newValue; /* check for entry (maybe not found...) */ if(! entry) return nerr_raise(NERR_NOT_FOUND, "Entry is NULL"); /* only use entry if not deleted */ if(! entry->deleted) { /* find item */ if((item = dictFindItem(dict, entry, id, FALSE))) { if(newval->value) { if(dict->freeValue) dict->freeValue(item->value, dict->freeRock); item->value = newval->value; } else if(newval->update) { /* track error (if update fails) */ err = newval->update(id, item->value, newval->rock); } else if((err = newval->new(id, newval->rock, &newValue)) == STATUS_OK) { if(dict->freeValue) dict->freeValue(item->value, dict->freeRock); item->value = newValue; } else { /* new item failed (don't remove old), indicate that update failed */ item = NULL; } } else { /* add new item to entry */ err = dictNewItem(dict, entry, id, newval, &item); } } /* release entry lock */ skipRelease(dict->list, lock); return nerr_pass(err); } static NEOERR *dictInsert(dictCtx dict, UINT32 hash, const char *id, dictValuePtr newval) { dictEntryPtr entry; void *lock; NEOERR *err = STATUS_OK; /* create new item and insert entry */ entry = calloc(1, sizeof(struct dictEntry)); if (entry == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory for dictEntry"); /* create/insert item (or cleanup) */ err = dictNewItem(dict, entry, id, newval, NULL); if (err != STATUS_OK) return nerr_pass(err); /* if we insert, we're done */ if((err = skipInsert(dict->list, hash, entry, FALSE)) == STATUS_OK) return STATUS_OK; /* failed to insert, cleanup */ if(dict->freeValue && ! newval->value) dict->freeValue(entry->first->value, dict->freeRock); free(entry->first->id); free(entry->first); free(entry); /* check err */ if (!nerr_handle(&err, NERR_DUPLICATE)) return nerr_pass(err); /* cool, someone already inserted the entry before we got the lock */ entry = skipSearch(dict->list, hash, &lock); /* update entry as normal (handles entry not found) */ return nerr_pass(dictUpdate(dict, entry, id, newval, lock)); } static UINT32 dictHash(dictCtx dict, const char *id) { UINT32 hash; hash = dict->hash(id) % DICT_HASH_BITS; /* ensure hash is valid for skiplist (modify consistently if not) */ if(! (hash && (hash != (UINT32)-1))) hash = 1; return hash; } static NEOERR *dictModify(dictCtx dict, const char *id, dictValuePtr newval) { NEOERR *err; UINT32 hash; dictEntryPtr entry; void *lock = NULL; hash = dictHash(dict, id); /* find entry in list */ entry = skipSearch(dict->list, hash, &lock); DICT_LOCK(dict); if((err = dictUpdate(dict, entry, id, newval, lock)) != STATUS_OK) { /* insert new entry */ nerr_ignore(&err); err = dictInsert(dict, hash, id, newval); } DICT_UNLOCK(dict); return nerr_pass(err); } NEOERR *dictSetValue(dictCtx dict, const char *id, void *value) { struct dictValue newval; assert(value); newval.value = value; return dictModify(dict, id, &newval); } NEOERR *dictModifyValue(dictCtx dict, const char *id, dictNewValueCB new, dictUpdateValueCB update, void *rock) { struct dictValue newval; if(! (new || update)) return FALSE; newval.value = NULL; newval.new = new; newval.update = update; newval.rock = rock; return dictModify(dict, id, &newval); } void dictReleaseLock(dictCtx dict, void *lock) { /* release entry */ DICT_UNLOCK(dict); /* release skip entry */ skipRelease(dict->list, lock); return; } void dictCleanup(dictCtx dict, dictCleanupFunc cleanup, void *rock) { dictItemPtr *prev, item, next; dictEntryPtr entry; UINT32 key = 0; void *lock; while((entry = skipNext(dict->list, &key, &lock))) { DICT_LOCK(dict); prev = &entry->first; for(item = entry->first; item; item = next) { next = item->next; if(cleanup(item->id, item->value, rock)) { /* remove item */ *prev = item->next; dictFreeItem(dict, item); } else { /* update reference pointer */ prev = &item->next; } } /* delete entry if last item removed */ if(! entry->first) { entry->deleted = TRUE; skipDelete(dict->list, key); } dictReleaseLock(dict, lock); } return; } void *dictSearch(dictCtx dict, const char *id, void **plock) { dictEntryPtr entry; dictItemPtr item; UINT32 hash; void *lock; void *value; hash = dictHash(dict, id); /* find entry in list */ if(! (entry = skipSearch(dict->list, hash, &lock))) return NULL; /* lock entry */ DICT_LOCK(dict); /* find item */ if((item = dictFindItem(dict, entry, id, FALSE))) { value = item->value; if(plock) *plock = lock; else dictReleaseLock(dict, lock); return value; } dictReleaseLock(dict, lock); return NULL; } void *dictNext (dictCtx dict, char **id, void **plock) { dictEntryPtr entry; dictItemPtr item; UINT32 hash; void *lock; void *value; /* Handle the first one special case */ if (*id == NULL) { hash = 0; /* find entry in list */ if(! (entry = skipNext (dict->list, &hash, &lock))) return NULL; /* lock entry */ DICT_LOCK(dict); /* Take first item in list */ item = entry->first; if (item != NULL) { value = item->value; *id = item->id; if(plock) *plock = lock; else dictReleaseLock(dict, lock); return value; } dictReleaseLock(dict, lock); return NULL; } else { hash = dictHash(dict, *id); /* find entry in list */ entry = skipSearch (dict->list, hash, &lock); if (entry == NULL) { entry = skipNext (dict->list, &hash, &lock); /* Not found, we're at the end of the dict */ if (entry == NULL) return NULL; } /* lock entry */ DICT_LOCK(dict); item = dictFindItem(dict, entry, *id, FALSE); if (item != NULL) { if (item->next != NULL) { item = item->next; } else { /* we have to move to the next skip entry */ entry = skipNext (dict->list, &hash, &lock); /* Not found, we're at the end of the dict */ item = entry?entry->first:NULL; if(! item) { dictReleaseLock(dict, lock); return NULL; } } value = item->value; *id = item->id; if(plock) *plock = lock; else dictReleaseLock(dict, lock); return value; } dictReleaseLock(dict, lock); } return NULL; } BOOL dictRemove(dictCtx dict, const char *id) { dictEntryPtr entry; dictItemPtr item; UINT32 hash; void *lock; hash = dictHash(dict, id); /* find entry in list */ if(! (entry = skipSearch(dict->list, hash, &lock))) return FALSE; /* lock entry */ DICT_LOCK(dict); /* find/unlink/free item */ if((item = dictFindItem(dict, entry, id, TRUE))) dictFreeItem(dict, item); dictReleaseLock(dict, lock); return item ? TRUE : FALSE; } /* called by skipList when safe to destroy entry */ static void dictDestroyEntry(void *value, void *ctx) { dictItemPtr item, next; dictEntryPtr entry; entry = value; for(item = entry->first; item; item = next) { next = item->next; dictFreeItem(ctx, item); item = next; } free(value); return; } NEOERR *dictCreate(dictCtx *rdict, BOOL threaded, UINT32 root, UINT32 maxLevel, UINT32 flushLimit, BOOL useCase, dictFreeValueFunc freeValue, void *freeRock) { NEOERR *err; dictCtx dict; *rdict = NULL; do { if(! (dict = calloc(1, sizeof(struct _dictCtx)))) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for dictCtx"); dict->useCase = useCase; dict->hash = python_string_hash; if(useCase) { dict->comp = strcmp; } else { /* dict->hash = uhashUpper; */ dict->comp = strcasecmp; } dict->threaded = threaded; dict->freeValue = freeValue; dict->freeRock = freeRock; err = skipNewList(&(dict->list), threaded, root, maxLevel, flushLimit, dictDestroyEntry, dict); if (err != STATUS_OK) break; if (threaded) { err = mCreate(&(dict->mList)); if (err != STATUS_OK) break; } *rdict = dict; return STATUS_OK; } while(FALSE); dictDestroy(dict); return nerr_pass(err); } void dictDestroy(dictCtx dict) { if(! dict) return; skipFreeList(dict->list); mDestroy(&dict->mList); free(dict); return; } clearsilver-0.10.5/util/dict.h0000644001211700116100000001526410261111216013074 00000000000000/* * * Thread-safe Dictionary Using String Identifiers * Copyright 1998-2000 Scott Shambarger (scott@shambarger.net) * * This software is open source. Permission to use, copy, modify, and * distribute this software for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies. No * warranty of any kind is expressed or implied. Use at your own risk. * */ #ifndef __DICT_H_ #define __DICT_H_ __BEGIN_DECLS typedef struct _dictCtx *dictCtx; typedef BOOL (*dictCleanupFunc)(char *id, void *value, void *rock); typedef void (*dictFreeValueFunc)(void *value, void *rock); NEOERR *dictCreate(dictCtx *dict, BOOL threaded, UINT32 root, UINT32 maxLevel, UINT32 flushLimit, BOOL useCase, dictFreeValueFunc freeValue, void *freeRock); /* * Function: dictCreate - create new dictionary. * Description: Returns a dictionary. If is true, list is * multi-thread safe. , , and * act as for skipNewList() (see skiplist.h) * Input: threaded - true if list should be thread-safe. * root - performance parameter (see above). * maxLevel - performance parameter (see above). * flushLimit - max deleted items to keep cached before * forcing a flush. * useCase - true to be case sensitive in identifiers * freeValue - callback when freeing a value * freeRock - context for freeValue callback * Output: None. * Return: New dictionary, NULL on error. * MT-Level: Safe. */ void dictDestroy(dictCtx dict); /* * Function: dictDestroy - destroy dictionary. * Description: Release all resources used by . * Input: dict - dictionary to destroy * Output: None. * Return: None. * MT-Level: Safe for unique . */ BOOL dictRemove(dictCtx dict, const char *id); /* * Function: dictRemove - remove item from dictionary. * Description: Removes item identified by from . * Input: dict - dictionary to search in. * id - identifier of item to remove. * Output: None. * Return: true if item found, false if not. * MT-Level: Safe if thread-safe. */ void *dictSearch(dictCtx dict, const char *id, void **plock); /* * Function: dictSearch - search for value in dictionary. * Description: Searches for in , and returns value if * found, or NULL if not. If is non-NULL, then * the lock returned in will be associated with * the returned value. Until this lock is passed to * dictReleaseLock(), the value will not be passed to the * dictCleanupFunc callback (see dictCleanup()). * Input: dict - dictionary to search in. * id - identifier of item to find. * plock - place for value lock (or NULL). * Output: plock - set to value lock. * Return: Value associated with , or NULL if not found. * MT-Level: Safe if thread-safe. */ void *dictNext(dictCtx dict, char **id, void **plock); /* * Function: dictNext - search for next value in dictionary. * Description: Can be used to iterate through values in the dictionary. * The order is the order of the hash of the ids, which * isn't usefully externally. Will return the value if * found, or NULL if not. If is non-NULL, then * the lock returned in will be associated with * the returned value. Until this lock is passed to * dictReleaseLock(), the value will not be passed to the * dictCleanupFunc callback (see dictCleanup()). * Input: dict - dictionary to iterate over. * id - pointer to identifier of last item found, or * pointer to NULL to retrieve first. * plock - place for value lock (or NULL). * Output: plock - set to value lock. * id - pointer to id of found value * Return: Value associated with , or NULL if not found. * MT-Level: Safe if thread-safe. */ void dictReleaseLock(dictCtx dict, void *lock); /* * Function: dictReleaseLock - release lock on value. * Description: Releases the lock on the value associated with . Once * the lock is released, the dictCleanupFunc callback can * be called for the value (see dictCleanup()). * Input: dict - dictionary containing value to release. * lock - lock to release. * Output: None. * Return: None. * MT-Level: Safe if thread-safe. */ NEOERR *dictSetValue(dictCtx dict, const char *id, void *value); /* * Function: dictSetValue - set/reset an items value. * Description: Updates the / pair into . * If is not in , it is created. * Input: dict - dictionary to add pair to. * id - identifier to insert/update * value - value to store (may NOT be NULL) * Output: None. * Return: true if inserted/updated, false if error * MT-Level: Safe if thread-safe. */ typedef NEOERR *(*dictNewValueCB)(const char *id, void *rock, void **new_val); typedef NEOERR *(*dictUpdateValueCB)(const char *id, void *value, void *rock); NEOERR *dictModifyValue(dictCtx dict, const char *id, dictNewValueCB new_cb, dictUpdateValueCB update, void *rock); /* * Function: dictModifyValue - create/modify an item. * Description: Finds 's value and calls . If is * not in , calls to obtain a new value. * Input: dict - dictionary to add pair to. * id - identifier of value * new - function to call to create new value (may be NULL) * update - function to call to modify value (if NULL, the old * value is freed, and is used) * rock - context to pass to or . * Output: None. * Return: true if inserted/updated, false if error * MT-Level: Safe if thread-safe. */ void dictCleanup(dictCtx dict, dictCleanupFunc cleanup, void *rock); /* * Function: dictCleanup - cleanup dictionary * Description: Calls for every item in . If * returns true, then item is removed from . * Input: dict - dictionary to cleanup * cleanup - cleanup callback * rock - to pass to * Output: None. * Return: None. * MT-Level: Safe if thread-safe. */ __END_DECLS #endif /* __DICT_H_ */ clearsilver-0.10.5/util/filter.c0000644001211700116100000001031210336774137013442 00000000000000/* based on concepts from the mutt filter code... * * This code basically does what popen should have been... and what * popen2/popen3/popen4 in python do... it allows you access to * as many of stdin/stdout/stderr for a sub program as you want, instead * of just one (which is what popen is). */ #include "cs_config.h" #include #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/filter.h" NEOERR *filter_wait (pid_t pid, int options, int *exitcode) { int r; pid_t rpid; rpid = waitpid (pid, &r, options); if (WIFEXITED(r)) { r = WEXITSTATUS(r); if (exitcode) { *exitcode = r; /* If they're asking for the exit code, we don't generate an error */ return STATUS_OK; } if (r == 0) return STATUS_OK; else return nerr_raise(NERR_SYSTEM, "Child %d returned status %d:", rpid, r); } if (WIFSIGNALED(r)) { r = WTERMSIG(r); return nerr_raise(NERR_SYSTEM, "Child %d died on signal %d:", rpid, r); } if (WIFSTOPPED(r)) { r = WSTOPSIG(r); return nerr_raise(NERR_SYSTEM, "Child %d stopped on signal %d:", rpid, r); } return nerr_raise(NERR_ASSERT, "ERROR: waitpid(%d, %d) returned (%d, %d)", pid, options, rpid, r); } NEOERR *filter_create_fd (const char *cmd, int *fdin, int *fdout, int *fderr, pid_t *pid) { int pi[2]={-1,-1}, po[2]={-1,-1}, pe[2]={-1,-1}; int rpid; *pid = 0; if (fdin) { *fdin = 0; if (pipe (pi) == -1) return nerr_raise_errno(NERR_SYSTEM, "Unable to open in pipe for command: %s", cmd); } if (fdout) { *fdout = 0; if (pipe (po) == -1) { if (fdin) { close (pi[0]); close (pi[1]); } return nerr_raise_errno(NERR_SYSTEM, "Unable to open out pipe for command: %s", cmd); } } if (fderr) { *fderr = 0; if (pipe (pe) == -1) { if (fdin) { close (pi[0]); close (pi[1]); } if (fdout) { close (po[0]); close (po[1]); } return nerr_raise_errno(NERR_SYSTEM, "Unable to open err pipe for command: %s", cmd); } } /* block signals */ if ((rpid = fork ()) == 0) { /* unblock signals */ if (fdin) { close (pi[1]); dup2 (pi[0], 0); close (pi[0]); } if (fdout) { close (po[0]); dup2 (po[1], 1); close (po[1]); } if (fderr) { close (pe[0]); dup2 (pe[1], 2); close (pe[1]); } execl ("/bin/sh", "sh", "-c", cmd, (void *)NULL); _exit (127); } else if (rpid == -1) { /* unblock signals */ if (fdin) { close (pi[0]); close (pi[1]); } if (fdout) { close (po[0]); close (po[1]); } if (fderr) { close (pe[0]); close (pe[1]); } return nerr_raise_errno(NERR_SYSTEM, "Unable to fork for command: %s", cmd); } if (fdout) { close (po[1]); *fdout = po[0]; } if (fdin) { close (pi[0]); *fdin = pi[1]; } if (fderr) { close (pe[1]); *fderr = pe[0]; } *pid = rpid; return STATUS_OK; } NEOERR *filter_create_fp(const char *cmd, FILE **in, FILE **out, FILE **err, pid_t *pid) { NEOERR *nerr; int fdin = 0, fdout = 0, fderr = 0; int *pfdin = NULL, *pfdout = NULL, *pfderr = NULL; if (in) pfdin = &fdin; if (out) pfdout = &fdout; if (err) pfderr = &fderr; nerr = filter_create_fd(cmd, pfdin, pfdout, pfderr, pid); if (nerr) return nerr_pass(nerr); if (in) { *in = fdopen (fdin, "w"); if (*in == NULL) return nerr_raise_errno(NERR_IO, "Unable to fdopen in for command: %s", cmd); } if (out) { *out = fdopen (fdout, "r"); if (*out == NULL) { if (in) fclose(*in); return nerr_raise_errno(NERR_IO, "Unable to fdopen out for command: %s", cmd); } } if (err) { *err = fdopen (fderr, "r"); if (*err == NULL) { if (in) fclose(*in); if (out) fclose(*out); return nerr_raise_errno(NERR_IO, "Unable to fdopen err for command: %s", cmd); } } return STATUS_OK; } clearsilver-0.10.5/util/filter.h0000644001211700116100000000737510261040275013450 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_FILTER_H_ #define __NEO_FILTER_H_ 1 __BEGIN_DECLS #include #include #include "util/neo_misc.h" #include "util/neo_err.h" /* * Function: filter_wait - wrap waitpid to decode the exitcode and why * your filter quit * Description: filter_wait wraps the waitpid call and raises an error * (with description) if the call failed. Note that if the * ask for the exitcode and the process exited with a code * other than zero, we don't raise an error. If you don't * ask for the exitcode, and it is non-zero, we raise an * error * Input: pid -> the process identifier to wait for * options -> the options to pass to waitpid (see wait(2)) * Output: exitcode -> the exitcode if the process existed normally * Returns: NERR_SYSTEM, NERR_ASSERT */ NEOERR *filter_wait(pid_t pid, int options, int *exitcode); /* * Function: filter_create_fd - Create a sub process and return the * requested pipes * Description: filter_create_fd and filter_create_fp are what popen * should have been: a mechanism to create sub processes * and have pipes to all their input/output. The concept * was taken from mutt, though python has something similar * with popen3/popen4. You control which pipes the * function returns by the fdin/fdout/fderr arguments. A * NULL value means "don't create a pipe", a pointer to an * int will cause the pipes to be created and the value * of the file descriptor stored in the int. You will have * to close(2) the file descriptors yourself. * Input: cmd -> the sub command to execute. Will be executed with * /bin/sh -c * fdin -> pointer to return the stdin pipe, or NULL if you don't * want the stdin pipe * fdout -> pointer to return the stdout pipe, or NULL if you don't * want the stdout pipe * fderr -> pointer to return the stderr pipe, or NULL if you don't * want the stderr pipe * Output: fdin -> the stdin file descriptor of the sub process * fdout -> the stdout file descriptor of the sub process * fderr -> the stderr file descriptor of the sub process * pid -> the pid of the sub process * Returns: NERR_SYSTEM */ NEOERR *filter_create_fd(const char *cmd, int *fdin, int *fdout, int *fderr, pid_t *pid); /* * Function: filter_create_fp - similar to filter_create_fd except with * buffered FILE* * Description: filter_create_fp is identical to filter_create_fd, * except each of the pipes is wrapped in a buffered stdio FILE * Input: cmd -> the sub command to execute. Will be executed with * /bin/sh -c * in -> pointer to return the stdin pipe, or NULL if you don't * want the stdin pipe * out -> pointer to return the stdout pipe, or NULL if you don't * want the stdout pipe * err -> pointer to return the stderr pipe, or NULL if you don't * want the stderr pipe * Output: in -> the stdin FILE of the sub process * out -> the stdout FILE of the sub process * err -> the stderr FILE of the sub process * pid -> the pid of the sub process * Returns: NERR_SYSTEM, NERR_IO */ NEOERR *filter_create_fp(const char *cmd, FILE **in, FILE **out, FILE **err, pid_t *pid); __END_DECLS #endif /* __NEO_FILTER_H_ */ clearsilver-0.10.5/util/missing.c0000644001211700116100000000363710261037516013630 00000000000000/* Missing Functions * * The functions included here are provided as replacements for system * library functions that are missing (or broken). * * Yes, configure usually tries to get you to have a single file for * each function, but pppbbbttthhhhh. * * To my knowledge, each of these replacement functions are available as * free code... if not, I'll have to steal them from somewhere else that * is free (hmm, FreeBSD libc?) */ #include "cs_config.h" #ifndef HAVE_STRTOK_R #include /* from glibc */ /* Parse S into tokens separated by characters in DELIM. If S is NULL, the saved pointer in SAVE_PTR is used as the next starting point. For example: char s[] = "-abc-=-def"; char *sp; x = strtok_r(s, "-", &sp); // x = "abc", sp = "=-def" x = strtok_r(NULL, "-=", &sp); // x = "def", sp = NULL x = strtok_r(NULL, "=", &sp); // x = NULL // s = "abc\0-def\0" */ char * strtok_r (char *s,const char * delim, char **save_ptr) { char *token; if (s == NULL) s = *save_ptr; /* Scan leading delimiters. */ s += strspn (s, delim); if (*s == '\0') { *save_ptr = s; return NULL; } /* Find the end of the token. */ token = s; s = strpbrk (token, delim); if (s == NULL) /* This token finishes the string. */ /**save_ptr = __rawmemchr (token, '\0');*/ *save_ptr = strchr (token, '\0'); else { /* Terminate the token and make * *SAVE_PTR point past it. */ *s = '\0'; *save_ptr = s + 1; } return token; } #endif #include #ifndef HAVE_LOCALTIME_R struct tm *localtime_r (const time_t *timep, struct tm *ttm) { ttm = localtime(timep); return ttm; } #endif #ifndef HAVE_GMTIME_R struct tm *gmtime_r(const time_t *timep, struct tm *ttm) { ttm = gmtime(timep); return ttm; } #endif #ifndef HAVE_MKSTEMP #include int mkstemp(char *path) { return open(mktemp(path),O_RDWR); } #endif clearsilver-0.10.5/util/neo_date.c0000644001211700116100000000510410405130065013715 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include "util/neo_misc.h" #include "neo_date.h" /* This is pretty much a HACK. Eventually, we might bring the parsing * and stuff into this library (we can use the public domain source code * from ftp://elsie.nci.nih.gov/pub/ as a base) * * For now, we just do a putenv(TZ)... which sucks, especially since * many versions of putenv do a strdup... and then leak the memory the * next time you putenv the same var. */ /* Since this is set to a partial filename and TZ=, it can't be bigger * than this */ static char TzBuf[_POSIX_PATH_MAX + 4]; static int time_set_tz (const char *mytimezone) { snprintf (TzBuf, sizeof(TzBuf), "TZ=%s", mytimezone); putenv(TzBuf); tzset(); return 0; } void neo_time_expand (const time_t tt, const char *mytimezone, struct tm *ttm) { const char *cur_tz = getenv("TZ"); int change_back = 0; if (cur_tz == NULL || strcmp(mytimezone, cur_tz)) { time_set_tz (mytimezone); change_back = 1; } localtime_r (&tt, ttm); if (cur_tz && change_back) { time_set_tz(cur_tz); } } time_t neo_time_compact (struct tm *ttm, const char *mytimezone) { time_t r; int save_isdst = ttm->tm_isdst; const char *cur_tz = getenv("TZ"); int change_back = 0; if (cur_tz == NULL || strcmp(mytimezone, cur_tz)) { time_set_tz (mytimezone); change_back = 1; } ttm->tm_isdst = -1; r = mktime(ttm); ttm->tm_isdst = save_isdst; if (cur_tz && change_back) { time_set_tz(cur_tz); } return r; } /* Hefted from NCSA HTTPd src/util.c -- What a pain in the ass. */ long neo_tz_offset(struct tm *ttm) { /* We assume here that HAVE_TM_ZONE implies HAVE_TM_GMTOFF and * HAVE_TZNAME implies HAVE_TIMEZONE since AC_STRUCT_TIMEZONE defines * the former and not the latter */ #if defined(HAVE_TM_ZONE) return ttm->tm_gmtoff; #elif defined(HAVE_TZNAME) long tz; #ifndef __CYGWIN__ tz = - timezone; #else tz = - _timezone; #endif if(ttm->tm_isdst) tz += 3600; return tz; #else long tz; struct tm loc_tm, gmt_tm; time_t tt; /* We probably shouldn't use the _r versions here since this * is for older platforms... */ tt = time(NULL); localtime_r(&tt, &loc_tm); gmtime_r(&tt, &gmt_tm); tz = mktime(&loc_tm) - mktime(&gmt_tm); return tz; #endif /* GMT OFFSet Crap */ } clearsilver-0.10.5/util/neo_date.h0000644001211700116100000000122110261040350013713 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_DATE_H_ #define __NEO_DATE_H_ 1 #include __BEGIN_DECLS /* UTC time_t -> struct tm in local timezone */ void neo_time_expand (const time_t tt, const char *timezone, struct tm *ttm); /* local timezone struct tm -> time_t UTC */ time_t neo_time_compact (struct tm *ttm, const char *timezone); /* To be portable... in seconds */ long neo_tz_offset(struct tm *ttm); __END_DECLS #endif /* __NEO_DATE_H_ */ clearsilver-0.10.5/util/neo_err.c0000644001211700116100000002333710403370145013603 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "ulist.h" #include "ulocks.h" int NERR_PASS = -1; int NERR_ASSERT = 0; int NERR_NOT_FOUND = 0; int NERR_DUPLICATE = 0; int NERR_NOMEM = 0; int NERR_PARSE = 0; int NERR_OUTOFRANGE = 0; int NERR_SYSTEM = 0; int NERR_IO = 0; int NERR_LOCK = 0; int NERR_DB = 0; int NERR_EXISTS = 0; static NEOERR *FreeList = NULL; static ULIST *Errors = NULL; static int Inited = 0; #ifdef HAVE_PTHREADS /* In multi-threaded environments, we have to init thread safely */ static pthread_mutex_t InitLock = PTHREAD_MUTEX_INITIALIZER; #endif /* Set this to 1 to enable non-thread safe re-use of NEOERR data * structures. This was a premature performance optimization that isn't * thread safe, if we want it thread safe we need to add mutex code... * which has its own performance penalties... */ static int UseFreeList = 0; static NEOERR *_err_alloc(void) { NEOERR *err; if (!UseFreeList || FreeList == NULL) { err = (NEOERR *)calloc (1, sizeof (NEOERR)); if (err == NULL) { ne_warn ("INTERNAL ERROR: Unable to allocate memory for NEOERR"); return INTERNAL_ERR; } return err; } else { err = FreeList; FreeList = FreeList->next; } err->flags |= NE_IN_USE; err->next = NULL; return err; } static int _err_free (NEOERR *err) { if (err == NULL || err == INTERNAL_ERR) return 0; if (err->next != NULL) _err_free(err->next); if (UseFreeList) { err->next = FreeList; FreeList = err; err->flags = 0; err->desc[0] = '\0'; } else { free(err); } return 0; } NEOERR *nerr_raisef (const char *func, const char *file, int lineno, int error, const char *fmt, ...) { NEOERR *err; va_list ap; err = _err_alloc(); if (err == INTERNAL_ERR) return err; va_start(ap, fmt); vsnprintf (err->desc, sizeof(err->desc), fmt, ap); va_end(ap); err->error = error; err->func = func; err->file = file; err->lineno = lineno; return err; } NEOERR *nerr_raise_errnof (const char *func, const char *file, int lineno, int error, const char *fmt, ...) { NEOERR *err; va_list ap; int l; err = _err_alloc(); if (err == INTERNAL_ERR) return err; va_start(ap, fmt); vsnprintf (err->desc, sizeof(err->desc), fmt, ap); va_end(ap); l = strlen(err->desc); snprintf (err->desc + l, sizeof(err->desc)-l, ": [%d] %s", errno, strerror (errno)); err->error = error; err->func = func; err->file = file; err->lineno = lineno; return err; } NEOERR *nerr_passf (const char *func, const char *file, int lineno, NEOERR *err) { NEOERR *nerr; if (err == STATUS_OK) return err; nerr = _err_alloc(); if (nerr == INTERNAL_ERR) return err; nerr->error = NERR_PASS; nerr->func = func; nerr->file = file; nerr->lineno = lineno; nerr->next = err; return nerr; } NEOERR *nerr_pass_ctxf (const char *func, const char *file, int lineno, NEOERR *err, const char *fmt, ...) { NEOERR *nerr; va_list ap; if (err == STATUS_OK) return err; nerr = _err_alloc(); if (nerr == INTERNAL_ERR) return err; va_start(ap, fmt); vsnprintf (nerr->desc, sizeof(nerr->desc), fmt, ap); va_end(ap); nerr->error = NERR_PASS; nerr->func = func; nerr->file = file; nerr->lineno = lineno; nerr->next = err; return nerr; } /* In the future, we'll allow someone to register an error handler */ void nerr_log_error (NEOERR *err) { NEOERR *more; char buf[1024]; char *err_name; if (err == STATUS_OK) return; if (err == INTERNAL_ERR) { ne_warn ("Internal error"); return; } more = err; fprintf (stderr, "Traceback (innermost last):\n"); while (more && more != INTERNAL_ERR) { err = more; more = err->next; if (err->error != NERR_PASS) { NEOERR *r; if (err->error == 0) { err_name = buf; snprintf (buf, sizeof (buf), "Unknown Error"); } else { r = uListGet (Errors, err->error - 1, (void *)&err_name); if (r != STATUS_OK) { err_name = buf; snprintf (buf, sizeof (buf), "Error %d", err->error); } } fprintf (stderr, " File \"%s\", line %d, in %s()\n%s: %s\n", err->file, err->lineno, err->func, err_name, err->desc); } else { fprintf (stderr, " File \"%s\", line %d, in %s()\n", err->file, err->lineno, err->func); if (err->desc[0]) { fprintf (stderr, " %s\n", err->desc); } } } } void nerr_error_string (NEOERR *err, STRING *str) { NEOERR *more; char buf[1024]; char *err_name; if (err == STATUS_OK) return; if (err == INTERNAL_ERR) { string_append (str, "Internal error"); return; } more = err; while (more && more != INTERNAL_ERR) { err = more; more = err->next; if (err->error != NERR_PASS) { NEOERR *r; if (err->error == 0) { err_name = buf; snprintf (buf, sizeof (buf), "Unknown Error"); } else { r = uListGet (Errors, err->error - 1, (void *)&err_name); if (r != STATUS_OK) { err_name = buf; snprintf (buf, sizeof (buf), "Error %d", err->error); } } string_appendf(str, "%s: %s", err_name, err->desc); return; } } } void nerr_error_traceback (NEOERR *err, STRING *str) { NEOERR *more; char buf[1024]; char buf2[1024]; char *err_name; if (err == STATUS_OK) return; if (err == INTERNAL_ERR) { string_append (str, "Internal error"); return; } more = err; string_append (str, "Traceback (innermost last):\n"); while (more && more != INTERNAL_ERR) { err = more; more = err->next; if (err->error != NERR_PASS) { NEOERR *r; if (err->error == 0) { err_name = buf; snprintf (buf, sizeof (buf), "Unknown Error"); } else { r = uListGet (Errors, err->error - 1, (void *)&err_name); if (r != STATUS_OK) { err_name = buf; snprintf (buf, sizeof (buf), "Error %d", err->error); } } snprintf (buf2, sizeof(buf2), " File \"%s\", line %d, in %s()\n%s: %s\n", err->file, err->lineno, err->func, err_name, err->desc); string_append(str, buf2); } else { snprintf (buf2, sizeof(buf2), " File \"%s\", line %d, in %s()\n", err->file, err->lineno, err->func); string_append(str, buf2); if (err->desc[0]) { snprintf (buf2, sizeof(buf2), " %s\n", err->desc); string_append(str, buf2); } } } } void nerr_ignore (NEOERR **err) { _err_free (*err); *err = STATUS_OK; } int nerr_handle (NEOERR **err, int etype) { NEOERR *walk = *err; while (walk != STATUS_OK && walk != INTERNAL_ERR) { if (walk->error == etype) { _err_free(*err); *err = STATUS_OK; return 1; } walk = walk->next; } if (walk == STATUS_OK && etype == STATUS_OK_INT) return 1; if (walk == STATUS_OK) return 0; if (walk == INTERNAL_ERR && etype == INTERNAL_ERR_INT) { *err = STATUS_OK; return 1; } if (walk == INTERNAL_ERR) return 0; return 0; } int nerr_match (NEOERR *err, int etype) { while (err != STATUS_OK && err != INTERNAL_ERR) { if (err->error == etype) return 1; err = err->next; } if (err == STATUS_OK && etype == STATUS_OK_INT) return 1; if (err == STATUS_OK) return 0; if (err == INTERNAL_ERR && etype == INTERNAL_ERR_INT) return 1; if (err == INTERNAL_ERR) return 0; return 0; } NEOERR *nerr_register (int *val, const char *name) { NEOERR *err; err = uListAppend (Errors, (void *) name); if (err != STATUS_OK) return nerr_pass(err); *val = uListLength(Errors); return STATUS_OK; } NEOERR *nerr_init (void) { NEOERR *err; if (Inited == 0) { #ifdef HAVE_PTHREADS /* In threaded environments, we have to mutex lock to do this init, but * we don't want to use a mutex every time to check that it was Inited. * So, we only lock if our first test of Inited was false */ err = mLock(&InitLock); if (err != STATUS_OK) return nerr_pass(err); if (Inited == 0) { #endif err = uListInit (&Errors, 10, 0); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_PASS, "InternalPass"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_ASSERT, "AssertError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_NOT_FOUND, "NotFoundError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_DUPLICATE, "DuplicateError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_NOMEM, "MemoryError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_PARSE, "ParseError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_OUTOFRANGE, "RangeError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_SYSTEM, "SystemError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_IO, "IOError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_LOCK, "LockError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_DB, "DBError"); if (err != STATUS_OK) return nerr_pass(err); err = nerr_register (&NERR_EXISTS, "ExistsError"); if (err != STATUS_OK) return nerr_pass(err); Inited = 1; #ifdef HAVE_PTHREADS } err = mUnlock(&InitLock); if (err != STATUS_OK) return nerr_pass(err); #endif } return STATUS_OK; } clearsilver-0.10.5/util/neo_err.h0000644001211700116100000001745010645315525013620 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_ERR_H_ #define __NEO_ERR_H_ 1 #include "util/neo_misc.h" /* For compilers (well, cpp actually) which don't define __PRETTY_FUNCTION__ */ #ifndef __GNUC__ #define __PRETTY_FUNCTION__ "unknown_function" #endif __BEGIN_DECLS /* For 64 bit systems which don't like mixing ints and pointers, we have the * _INT version for doing that comparison */ #define STATUS_OK ((NEOERR *)0) #define STATUS_OK_INT 0 #define INTERNAL_ERR ((NEOERR *)1) #define INTERNAL_ERR_INT 1 /* NEOERR flags */ #define NE_IN_USE (1<<0) typedef int NERR_TYPE; /* Predefined Error Types - These are all registered in nerr_init */ extern NERR_TYPE NERR_PASS; extern NERR_TYPE NERR_ASSERT; extern NERR_TYPE NERR_NOT_FOUND; extern NERR_TYPE NERR_DUPLICATE; extern NERR_TYPE NERR_NOMEM; extern NERR_TYPE NERR_PARSE; extern NERR_TYPE NERR_OUTOFRANGE; extern NERR_TYPE NERR_SYSTEM; extern NERR_TYPE NERR_IO; extern NERR_TYPE NERR_LOCK; extern NERR_TYPE NERR_DB; extern NERR_TYPE NERR_EXISTS; typedef struct _neo_err { int error; int err_stack; int flags; char desc[256]; const char *file; const char *func; int lineno; /* internal use only */ struct _neo_err *next; } NEOERR; /* Technically, we could do this in configure and detect what their compiler * can handle, but for now... */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define USE_C99_VARARG_MACROS 1 #elif __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 4) || defined (S_SPLINT_S) #define USE_GNUC_VARARG_MACROS 1 #else #error The compiler is missing support for variable-argument macros. #endif /* * function: nerr_raise * description: Use this method to create an error "exception" for * return up the call chain * arguments: using the macro, the function name, file, and lineno are * automagically recorded for you. You just provide the * error (from those listed above) and the printf-style * reason. THIS IS A PRINTF STYLE FUNCTION, DO NOT PASS * UNKNOWN STRING DATA AS THE FORMAT STRING. * returns: a pointer to a NEOERR, or INTERNAL_ERR if allocation of * NEOERR fails */ #if defined(USE_C99_VARARG_MACROS) #define nerr_raise(e,f,...) \ nerr_raisef(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,__VA_ARGS__) #elif defined(USE_GNUC_VARARG_MACROS) #define nerr_raise(e,f,a...) \ nerr_raisef(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,##a) #endif NEOERR *nerr_raisef (const char *func, const char *file, int lineno, NERR_TYPE error, const char *fmt, ...) ATTRIBUTE_PRINTF(5,6); #if defined(USE_C99_VARARG_MACROS) #define nerr_raise_errno(e,f,...) \ nerr_raise_errnof(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,__VA_ARGS__) #elif defined(USE_GNUC_VARARG_MACROS) #define nerr_raise_errno(e,f,a...) \ nerr_raise_errnof(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,##a) #endif NEOERR *nerr_raise_errnof (const char *func, const char *file, int lineno, int error, const char *fmt, ...) ATTRIBUTE_PRINTF(5,6); /* function: nerr_pass * description: this function is used to pass an error up a level in the * call chain (ie, if the error isn't handled at the * current level). This allows us to track the traceback * of the error. * arguments: with the macro, the function name, file and lineno are * automagically recorded. Just pass the error. * returns: a pointer to an error */ #define nerr_pass(e) \ nerr_passf(__PRETTY_FUNCTION__,__FILE__,__LINE__,e) NEOERR *nerr_passf (const char *func, const char *file, int lineno, NEOERR *err); /* function: nerr_pass_ctx * description: this function is used to pass an error up a level in the * call chain (ie, if the error isn't handled at the * current level). This allows us to track the traceback * of the error. * This version includes context information about lower * errors * arguments: with the macro, the function name, file and lineno are * automagically recorded. Just pass the error and * a printf format string giving more information about where * the error is occuring. * returns: a pointer to an error */ #if defined(USE_C99_VARARG_MACROS) #define nerr_pass_ctx(e,f,...) \ nerr_pass_ctxf(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,__VA_ARGS__) #elif defined(USE_GNUC_VARARG_MACROS) #define nerr_pass_ctx(e,f,a...) \ nerr_pass_ctxf(__PRETTY_FUNCTION__,__FILE__,__LINE__,e,f,##a) #endif NEOERR *nerr_pass_ctxf (const char *func, const char *file, int lineno, NEOERR *err, const char *fmt, ...) ATTRIBUTE_PRINTF(5,6); /* function: nerr_log_error * description: currently, this prints out the error to stderr, and * free's the error chain */ void nerr_log_error (NEOERR *err); #include "util/neo_str.h" /* function: nerr_error_string * description: returns the string associated with an error (the bottom * level of the error chain) * arguments: err - error * str - string to which the data is appended * returns: None - errors appending to the string are ignored */ void nerr_error_string (NEOERR *err, STRING *str); /* function: nerr_error_traceback * description: returns the full traceback of the error chain * arguments: err - error * str - string to which the data is appended * returns: None - errors appending to the string are ignored */ void nerr_error_traceback (NEOERR *err, STRING *str); /* function: nerr_ignore * description: you should only call this if you actually handle the * error (should I rename it?). Free's the error chain. */ void nerr_ignore (NEOERR **err); /* function: nerr_register * description: register an error type. This will assign a numeric value * to the type, and keep track of the "pretty name" for it. * arguments: err - pointer to a NERR_TYPE * name - pretty name for the error type * returns: NERR_NOMEM on no memory */ NEOERR *nerr_register (NERR_TYPE *err, const char *name); /* function: nerr_init * description: initialize the NEOERR system. Can be called more than once. * Is not thread safe. This registers all of the built in * error types as defined at the top of this file. If you don't * call this, all exceptions will be returned as UnknownError. * arguments: None * returns: possibly NERR_NOMEM, but somewhat unlikely. Possibly an * UnknownError if NERR_NOMEM hasn't been registered yet. */ NEOERR *nerr_init (void); /* function: nerr_match * description: nerr_match is used to walk the NEOERR chain and match * the error against a specific error type. In exception * parlance, this would be the equivalent of "catch". * Typically, you can just compare a NEOERR against STATUS_OK * or just test for true if you are checking for any error. * arguments: err - the NEOERR that has an error. * type - the NEOERR type, as registered with nerr_register * returns: true on match */ int nerr_match (NEOERR *err, NERR_TYPE type); /* function: nerr_handle * description: nerr_handle is a convenience function. It is the equivalent * of nerr_match, but it will also deallocate the error chain * on a match. * arguments: err - pointer to a pointer NEOERR * type - the NEOERR type, as registered with nerr_register * returns: true on match */ int nerr_handle (NEOERR **err, NERR_TYPE type); __END_DECLS #endif /* __NEO_ERR_H_ */ clearsilver-0.10.5/util/neo_files.c0000644001211700116100000001261310645307177014125 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_files.h" #include "wildmat.h" NEOERR *ne_mkdirs (const char *path, mode_t mode) { char mypath[_POSIX_PATH_MAX]; int x; int r; strncpy (mypath, path, sizeof(mypath)); x = strlen(mypath); if ((x < sizeof(mypath)) && (mypath[x-1] != '/')) { mypath[x] = '/'; mypath[x+1] = '\0'; } for (x = 1; mypath[x]; x++) { if (mypath[x] == '/') { mypath[x] = '\0'; #ifdef __MINGW32__ /* Braindead MINGW32 doesn't just have a dummy argument for mode */ r = mkdir (mypath); #else r = mkdir (mypath, mode); #endif if (r == -1 && errno != EEXIST) { return nerr_raise_errno(NERR_SYSTEM, "ne_mkdirs: mkdir(%s, %x) failed", mypath, mode); } mypath[x] = '/'; } } return STATUS_OK; } NEOERR *ne_load_file_len (const char *path, char **str, int *out_len) { struct stat s; int fd; int len; int bytes_read; *str = NULL; if (out_len) *out_len = 0; if (stat(path, &s) == -1) { if (errno == ENOENT) return nerr_raise (NERR_NOT_FOUND, "File %s not found", path); return nerr_raise_errno (NERR_SYSTEM, "Unable to stat file %s", path); } fd = open (path, O_RDONLY); if (fd == -1) { return nerr_raise_errno (NERR_SYSTEM, "Unable to open file %s", path); } len = s.st_size; *str = (char *) malloc (len + 1); if (*str == NULL) { close(fd); return nerr_raise (NERR_NOMEM, "Unable to allocate memory (%d) to load file %s", len + 1, path); } if ((bytes_read = read (fd, *str, len)) == -1) { close(fd); free(*str); return nerr_raise_errno (NERR_SYSTEM, "Unable to read file %s", path); } (*str)[bytes_read] = '\0'; close(fd); if (out_len) *out_len = bytes_read; return STATUS_OK; } NEOERR *ne_load_file (const char *path, char **str) { return ne_load_file_len (path, str, NULL); } NEOERR *ne_save_file (const char *path, char *str) { NEOERR *err; int fd; int w, l; fd = open (path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP ); if (fd == -1) { return nerr_raise_errno (NERR_IO, "Unable to create file %s", path); } l = strlen(str); w = write (fd, str, l); if (w != l) { err = nerr_raise_errno (NERR_IO, "Unable to write file %s", path); close (fd); return err; } close (fd); return STATUS_OK; } NEOERR *ne_remove_dir (const char *path) { NEOERR *err; DIR *dp; struct stat s; struct dirent *de; char npath[_POSIX_PATH_MAX]; if (stat(path, &s) == -1) { if (errno == ENOENT) return STATUS_OK; return nerr_raise_errno (NERR_SYSTEM, "Unable to stat file %s", path); } if (!S_ISDIR(s.st_mode)) { return nerr_raise (NERR_ASSERT, "Path %s is not a directory", path); } dp = opendir(path); if (dp == NULL) return nerr_raise_errno (NERR_IO, "Unable to open directory %s", path); while ((de = readdir (dp)) != NULL) { if (strcmp(de->d_name, ".") && strcmp(de->d_name, "..")) { snprintf (npath, sizeof(npath), "%s/%s", path, de->d_name); if (stat(npath, &s) == -1) { if (errno == ENOENT) continue; closedir(dp); return nerr_raise_errno (NERR_SYSTEM, "Unable to stat file %s", npath); } if (S_ISDIR(s.st_mode)) { err = ne_remove_dir(npath); if (err) break; } else { if (unlink(npath) == -1) { if (errno == ENOENT) continue; closedir(dp); return nerr_raise_errno (NERR_SYSTEM, "Unable to unlink file %s", npath); } } } } closedir(dp); if (rmdir(path) == -1) { return nerr_raise_errno (NERR_SYSTEM, "Unable to rmdir %s", path); } return STATUS_OK; } NEOERR *ne_listdir(const char *path, ULIST **files) { return nerr_pass(ne_listdir_fmatch(path, files, NULL, NULL)); } static int _glob_match(void *rock, const char *filename) { return wildmat(filename, rock); } NEOERR *ne_listdir_match(const char *path, ULIST **files, const char *match) { return nerr_pass(ne_listdir_fmatch(path, files, _glob_match, (void *)match)); } NEOERR *ne_listdir_fmatch(const char *path, ULIST **files, MATCH_FUNC fmatch, void *rock) { DIR *dp; struct dirent *de; ULIST *myfiles = NULL; NEOERR *err = STATUS_OK; if (files == NULL) return nerr_raise(NERR_ASSERT, "Invalid call to ne_listdir_fmatch"); if (*files == NULL) { err = uListInit(&myfiles, 10, 0); if (err) return nerr_pass(err); } else { myfiles = *files; } if ((dp = opendir (path)) == NULL) { return nerr_raise_errno(NERR_IO, "Unable to opendir %s", path); } while ((de = readdir (dp)) != NULL) { if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; if (fmatch != NULL && !fmatch(rock, de->d_name)) continue; err = uListAppend(myfiles, strdup(de->d_name)); if (err) break; } closedir(dp); if (err && *files == NULL) { uListDestroy(&myfiles, ULIST_FREE); } else if (*files == NULL) { *files = myfiles; } return nerr_pass(err); } clearsilver-0.10.5/util/neo_files.h0000644001211700116100000000172410261040677014124 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_FILES_H_ #define __NEO_FILES_H_ 1 __BEGIN_DECLS #include #include #include "util/ulist.h" typedef int (* MATCH_FUNC)(void *rock, const char *filename); NEOERR *ne_mkdirs (const char *path, mode_t mode); NEOERR *ne_load_file (const char *path, char **str); NEOERR *ne_load_file_len (const char *path, char **str, int *len); NEOERR *ne_save_file (const char *path, char *str); NEOERR *ne_remove_dir (const char *path); NEOERR *ne_listdir(const char *path, ULIST **files); NEOERR *ne_listdir_match(const char *path, ULIST **files, const char *match); NEOERR *ne_listdir_fmatch(const char *path, ULIST **files, MATCH_FUNC fmatch, void *rock); __END_DECLS #endif /* __NEO_FILES_H_ */ clearsilver-0.10.5/util/neo_hash.c0000644001211700116100000001276510515537544013755 00000000000000/* * Copyright 2003-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_hash.h" static NEOERR *_hash_resize(NE_HASH *hash); static NE_HASHNODE **_hash_lookup_node (NE_HASH *hash, void *key, UINT32 *hashv); NEOERR *ne_hash_init (NE_HASH **hash, NE_HASH_FUNC hash_func, NE_COMP_FUNC comp_func) { NE_HASH *my_hash = NULL; my_hash = (NE_HASH *) calloc(1, sizeof(NE_HASH)); if (my_hash == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NE_HASH"); my_hash->size = 256; my_hash->num = 0; my_hash->hash_func = hash_func; my_hash->comp_func = comp_func; my_hash->nodes = (NE_HASHNODE **) calloc (my_hash->size, sizeof(NE_HASHNODE *)); if (my_hash->nodes == NULL) { free(my_hash); return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NE_HASHNODES"); } *hash = my_hash; return STATUS_OK; } void ne_hash_destroy (NE_HASH **hash) { NE_HASH *my_hash; NE_HASHNODE *node, *next; int x; if (hash == NULL || *hash == NULL) return; my_hash = *hash; for (x = 0; x < my_hash->size; x++) { node = my_hash->nodes[x]; while (node) { next = node->next; free(node); node = next; } } free(my_hash->nodes); my_hash->nodes = NULL; free(my_hash); *hash = NULL; } NEOERR *ne_hash_insert(NE_HASH *hash, void *key, void *value) { UINT32 hashv; NE_HASHNODE **node; node = _hash_lookup_node(hash, key, &hashv); if (*node) { (*node)->value = value; } else { *node = (NE_HASHNODE *) malloc(sizeof(NE_HASHNODE)); if (node == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate NE_HASHNODE"); (*node)->hashv = hashv; (*node)->key = key; (*node)->value = value; (*node)->next = NULL; } hash->num++; return _hash_resize(hash); } void *ne_hash_lookup(NE_HASH *hash, void *key) { NE_HASHNODE *node; node = *_hash_lookup_node(hash, key, NULL); return (node) ? node->value : NULL; } void *ne_hash_remove(NE_HASH *hash, void *key) { NE_HASHNODE **node, *remove; void *value = NULL; node = _hash_lookup_node(hash, key, NULL); if (*node) { remove = *node; *node = remove->next; value = remove->value; free(remove); hash->num--; } return value; } int ne_hash_has_key(NE_HASH *hash, void *key) { NE_HASHNODE *node; node = *_hash_lookup_node(hash, key, NULL); if (node) return 1; return 0; } void *ne_hash_next(NE_HASH *hash, void **key) { NE_HASHNODE **node = 0; UINT32 hashv, bucket; if (*key) { node = _hash_lookup_node(hash, key, NULL); if (*node) { bucket = (*node)->hashv & (hash->size - 1); } else { hashv = hash->hash_func(*key); bucket = hashv & (hash->size - 1); } } else { bucket = 0; } if (*node) { if ((*node)->next) { *key = (*node)->next->key; return (*node)->next->value; } bucket++; } while (bucket < hash->size) { if (hash->nodes[bucket]) { *key = hash->nodes[bucket]->key; return hash->nodes[bucket]->value; } bucket++; } return NULL; } static NE_HASHNODE **_hash_lookup_node (NE_HASH *hash, void *key, UINT32 *o_hashv) { UINT32 hashv, bucket; NE_HASHNODE **node; hashv = hash->hash_func(key); if (o_hashv) *o_hashv = hashv; bucket = hashv & (hash->size - 1); /* ne_warn("Lookup %s %d %d", key, hashv, bucket); */ node = &(hash->nodes[bucket]); if (hash->comp_func) { while (*node && !(hash->comp_func((*node)->key, key))) node = &(*node)->next; } else { /* No comp_func means we're doing pointer comparisons */ while (*node && (*node)->key != key) node = &(*node)->next; } /* ne_warn("Node %x", node); */ return node; } /* Ok, we're doing some weirdness here... */ static NEOERR *_hash_resize(NE_HASH *hash) { NE_HASHNODE **new_nodes; NE_HASHNODE *entry, *prev; int x, next_bucket; int orig_size = hash->size; UINT32 hash_mask; if (hash->size > hash->num) return STATUS_OK; /* We always double in size */ new_nodes = (NE_HASHNODE **) realloc (hash->nodes, (hash->size*2) * sizeof(NE_HASHNODE)); if (new_nodes == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory to resize NE_HASH"); hash->nodes = new_nodes; orig_size = hash->size; hash->size = hash->size*2; /* Initialize new parts */ for (x = orig_size; x < hash->size; x++) { hash->nodes[x] = NULL; } hash_mask = hash->size - 1; for (x = 0; x < orig_size; x++) { prev = NULL; next_bucket = x + orig_size; for (entry = hash->nodes[x]; entry; entry = prev ? prev->next : hash->nodes[x]) { if ((entry->hashv & hash_mask) != x) { if (prev) { prev->next = entry->next; } else { hash->nodes[x] = entry->next; } entry->next = hash->nodes[next_bucket]; hash->nodes[next_bucket] = entry; } else { prev = entry; } } } return STATUS_OK; } int ne_hash_str_comp(const void *a, const void *b) { return !strcmp((const char *)a, (const char *)b); } UINT32 ne_hash_str_hash(const void *a) { return ne_crc((unsigned char *)a, strlen((const char *)a)); } int ne_hash_int_comp(const void *a, const void *b) { if (a == b) return 1; return 0; } UINT32 ne_hash_int_hash(const void *a) { return (UINT32)(long)(a); } clearsilver-0.10.5/util/neo_hash.h0000644001211700116100000000243210261037517013741 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_HASH_H_ #define __NEO_HASH_H_ 1 __BEGIN_DECLS #include #include "util/neo_misc.h" typedef UINT32 (*NE_HASH_FUNC)(const void *); typedef int (*NE_COMP_FUNC)(const void *, const void *); typedef struct _NE_HASHNODE { void *key; void *value; UINT32 hashv; struct _NE_HASHNODE *next; } NE_HASHNODE; typedef struct _HASH { UINT32 size; UINT32 num; NE_HASHNODE **nodes; NE_HASH_FUNC hash_func; NE_COMP_FUNC comp_func; } NE_HASH; NEOERR *ne_hash_init (NE_HASH **hash, NE_HASH_FUNC hash_func, NE_COMP_FUNC comp_func); void ne_hash_destroy (NE_HASH **hash); NEOERR *ne_hash_insert(NE_HASH *hash, void *key, void *value); void *ne_hash_lookup(NE_HASH *hash, void *key); int ne_hash_has_key(NE_HASH *hash, void *key); void *ne_hash_remove(NE_HASH *hash, void *key); void *ne_hash_next(NE_HASH *hash, void **key); int ne_hash_str_comp(const void *a, const void *b); UINT32 ne_hash_str_hash(const void *a); int ne_hash_int_comp(const void *a, const void *b); UINT32 ne_hash_int_hash(const void *a); __END_DECLS #endif /* __NEO_HASH_H_ */ clearsilver-0.10.5/util/neo_hdf.c0000644001211700116100000011507310645304545013564 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_rand.h" #include "neo_hdf.h" #include "neo_str.h" #include "neo_files.h" #include "ulist.h" /* Ok, in order to use the hash, we have to support n-len strings * instead of null terminated strings (since in set_value and walk_hdf * we are merely using part of the HDF name for lookup, and that might * be a const, and we don't want the overhead of allocating/copying * that data out...) * * Since HASH doesn't maintain any data placed in it, merely pointers to * it, we use the HDF node itself as the key, and have specific * comp/hash functions which just use the name/name_len as the key. */ static int hash_hdf_comp(const void *a, const void *b) { HDF *ha = (HDF *)a; HDF *hb = (HDF *)b; return (ha->name_len == hb->name_len) && !strncmp(ha->name, hb->name, ha->name_len); } static UINT32 hash_hdf_hash(const void *a) { HDF *ha = (HDF *)a; return ne_crc((UINT8 *)(ha->name), ha->name_len); } static NEOERR *_alloc_hdf (HDF **hdf, const char *name, size_t nlen, const char *value, int dup, int wf, HDF *top) { *hdf = calloc (1, sizeof (HDF)); if (*hdf == NULL) { return nerr_raise (NERR_NOMEM, "Unable to allocate memory for hdf element"); } (*hdf)->top = top; if (name != NULL) { (*hdf)->name_len = nlen; (*hdf)->name = (char *) malloc (nlen + 1); if ((*hdf)->name == NULL) { free((*hdf)); (*hdf) = NULL; return nerr_raise (NERR_NOMEM, "Unable to allocate memory for hdf element: %s", name); } strncpy((*hdf)->name, name, nlen); (*hdf)->name[nlen] = '\0'; } if (value != NULL) { if (dup) { (*hdf)->alloc_value = 1; (*hdf)->value = strdup(value); if ((*hdf)->value == NULL) { free((*hdf)->name); free((*hdf)); (*hdf) = NULL; return nerr_raise (NERR_NOMEM, "Unable to allocate memory for hdf element %s", name); } } else { (*hdf)->alloc_value = wf; /* We're overriding the const of value here for the set_buf case * where we overrode the char * to const char * earlier, since * alloc_value actually keeps track of the const-ness for us */ (*hdf)->value = (char *)value; } } return STATUS_OK; } static void _dealloc_hdf_attr(HDF_ATTR **attr) { HDF_ATTR *next; while ((*attr) != NULL) { next = (*attr)->next; if ((*attr)->key) free((*attr)->key); if ((*attr)->value) free((*attr)->value); free(*attr); *attr = next; } *attr = NULL; } static void _dealloc_hdf (HDF **hdf) { HDF *myhdf = *hdf; HDF *next = NULL; if (myhdf == NULL) return; if (myhdf->child != NULL) _dealloc_hdf(&(myhdf->child)); /* This was easier recursively, but dangerous on long lists, so we * walk it ourselves */ next = myhdf->next; while (next != NULL) { myhdf->next = next->next; next->next = NULL; _dealloc_hdf(&next); next = myhdf->next; } if (myhdf->name != NULL) { free (myhdf->name); myhdf->name = NULL; } if (myhdf->value != NULL) { if (myhdf->alloc_value) free (myhdf->value); myhdf->value = NULL; } if (myhdf->attr != NULL) { _dealloc_hdf_attr(&(myhdf->attr)); } if (myhdf->hash != NULL) { ne_hash_destroy(&myhdf->hash); } free(myhdf); *hdf = NULL; } NEOERR* hdf_init (HDF **hdf) { NEOERR *err; HDF *my_hdf; *hdf = NULL; err = nerr_init(); if (err != STATUS_OK) return nerr_pass (err); err = _alloc_hdf (&my_hdf, NULL, 0, NULL, 0, 0, NULL); if (err != STATUS_OK) return nerr_pass (err); my_hdf->top = my_hdf; *hdf = my_hdf; return STATUS_OK; } void hdf_destroy (HDF **hdf) { if (*hdf == NULL) return; if ((*hdf)->top == (*hdf)) { _dealloc_hdf(hdf); } } static int _walk_hdf (HDF *hdf, const char *name, HDF **node) { HDF *parent = NULL; HDF *hp = hdf; HDF hash_key; int x = 0; const char *s, *n; int r; *node = NULL; if (hdf == NULL) return -1; if (name == NULL || name[0] == '\0') { *node = hdf; return 0; } if (hdf->link) { r = _walk_hdf (hdf->top, hdf->value, &hp); if (r) return r; if (hp) { parent = hp; hp = hp->child; } } else { parent = hdf; hp = hdf->child; } if (hp == NULL) { return -1; } n = name; s = strchr (n, '.'); x = (s == NULL) ? strlen(n) : s - n; while (1) { if (parent && parent->hash) { hash_key.name = (char *)n; hash_key.name_len = x; hp = ne_hash_lookup(parent->hash, &hash_key); } else { while (hp != NULL) { if (hp->name && (x == hp->name_len) && !strncmp(hp->name, n, x)) { break; } else { hp = hp->next; } } } if (hp == NULL) { return -1; } if (s == NULL) break; if (hp->link) { r = _walk_hdf (hp->top, hp->value, &hp); if (r) { return r; } parent = hp; hp = hp->child; } else { parent = hp; hp = hp->child; } n = s + 1; s = strchr (n, '.'); x = (s == NULL) ? strlen(n) : s - n; } if (hp->link) { return _walk_hdf (hp->top, hp->value, node); } *node = hp; return 0; } int hdf_get_int_value (HDF *hdf, const char *name, int defval) { HDF *node; int v; char *n; if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL)) { v = strtol (node->value, &n, 10); if (node->value == n) v = defval; return v; } return defval; } /* This should return a const char *, but changing this would have big * repurcussions for any C code using this function, so no change for now */ char* hdf_get_value (HDF *hdf, const char *name, const char *defval) { HDF *node; if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL)) { return node->value; } return (char *)defval; } char* hdf_get_valuevf (HDF *hdf, const char *namefmt, va_list ap) { HDF *node; char *name; name = vsprintf_alloc(namefmt, ap); if (name == NULL) return NULL; if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL)) { free(name); return node->value; } free(name); return NULL; } char* hdf_get_valuef (HDF *hdf, const char *namefmt, ...) { char *val; va_list ap; va_start(ap, namefmt); val = hdf_get_valuevf(hdf, namefmt, ap); va_end(ap); return val; } NEOERR* hdf_get_copy (HDF *hdf, const char *name, char **value, const char *defval) { HDF *node; if ((_walk_hdf(hdf, name, &node) == 0) && (node->value != NULL)) { *value = strdup(node->value); if (*value == NULL) { return nerr_raise (NERR_NOMEM, "Unable to allocate copy of %s", name); } } else { if (defval == NULL) *value = NULL; else { *value = strdup(defval); if (*value == NULL) { return nerr_raise (NERR_NOMEM, "Unable to allocate copy of %s", name); } } } return STATUS_OK; } HDF* hdf_get_obj (HDF *hdf, const char *name) { HDF *obj; _walk_hdf(hdf, name, &obj); return obj; } HDF* hdf_get_child (HDF *hdf, const char *name) { HDF *obj; _walk_hdf(hdf, name, &obj); if (obj != NULL) return obj->child; return obj; } HDF_ATTR* hdf_get_attr (HDF *hdf, const char *name) { HDF *obj; _walk_hdf(hdf, name, &obj); if (obj != NULL) return obj->attr; return NULL; } NEOERR* hdf_set_attr (HDF *hdf, const char *name, const char *key, const char *value) { HDF *obj; HDF_ATTR *attr, *last; _walk_hdf(hdf, name, &obj); if (obj == NULL) return nerr_raise(NERR_ASSERT, "Unable to set attribute on none existant node"); if (obj->attr != NULL) { attr = obj->attr; last = attr; while (attr != NULL) { if (!strcmp(attr->key, key)) { if (attr->value) free(attr->value); /* a set of NULL deletes the attr */ if (value == NULL) { if (attr == obj->attr) obj->attr = attr->next; else last->next = attr->next; free(attr->key); free(attr); return STATUS_OK; } attr->value = strdup(value); if (attr->value == NULL) return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value); return STATUS_OK; } last = attr; attr = attr->next; } last->next = (HDF_ATTR *) calloc(1, sizeof(HDF_ATTR)); if (last->next == NULL) return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value); attr = last->next; } else { if (value == NULL) return STATUS_OK; obj->attr = (HDF_ATTR *) calloc(1, sizeof(HDF_ATTR)); if (obj->attr == NULL) return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value); attr = obj->attr; } attr->key = strdup(key); attr->value = strdup(value); if (attr->key == NULL || attr->value == NULL) return nerr_raise(NERR_NOMEM, "Unable to set attr %s to %s", key, value); return STATUS_OK; } HDF* hdf_obj_child (HDF *hdf) { HDF *obj; if (hdf == NULL) return NULL; if (hdf->link) { if (_walk_hdf(hdf->top, hdf->value, &obj)) return NULL; return obj->child; } return hdf->child; } HDF* hdf_obj_next (HDF *hdf) { if (hdf == NULL) return NULL; return hdf->next; } HDF* hdf_obj_top (HDF *hdf) { if (hdf == NULL) return NULL; return hdf->top; } HDF_ATTR* hdf_obj_attr (HDF *hdf) { if (hdf == NULL) return NULL; return hdf->attr; } char* hdf_obj_name (HDF *hdf) { if (hdf == NULL) return NULL; return hdf->name; } char* hdf_obj_value (HDF *hdf) { int count = 0; if (hdf == NULL) return NULL; while (hdf->link && count < 100) { if (_walk_hdf (hdf->top, hdf->value, &hdf)) return NULL; count++; } return hdf->value; } void _merge_attr (HDF_ATTR *dest, HDF_ATTR *src) { HDF_ATTR *da, *ld; HDF_ATTR *sa, *ls; BOOL found; sa = src; ls = src; while (sa != NULL) { da = dest; ld = da; found = 0; while (da != NULL) { if (!strcmp(da->key, sa->key)) { if (da->value) free(da->value); da->value = sa->value; sa->value = NULL; found = 1; break; } ld = da; da = da->next; } if (!found) { ld->next = sa; ls->next = sa->next; if (src == sa) src = sa->next; ld->next->next = NULL; sa = ls->next; } else { ls = sa; sa = sa->next; } } _dealloc_hdf_attr(&src); } NEOERR* _hdf_hash_level(HDF *hdf) { NEOERR *err; HDF *child; err = ne_hash_init(&(hdf->hash), hash_hdf_hash, hash_hdf_comp); if (err) return nerr_pass(err); child = hdf->child; while (child) { err = ne_hash_insert(hdf->hash, child, child); if (err) return nerr_pass(err); child = child->next; } return STATUS_OK; } static NEOERR* _set_value (HDF *hdf, const char *name, const char *value, int dup, int wf, int link, HDF_ATTR *attr, HDF **set_node) { NEOERR *err; HDF *hn, *hp, *hs; HDF hash_key; int x = 0; const char *s = name; const char *n = name; int count = 0; if (set_node != NULL) *set_node = NULL; if (hdf == NULL) { return nerr_raise(NERR_ASSERT, "Unable to set %s on NULL hdf", name); } /* HACK: allow setting of this node by passing an empty name */ if (name == NULL || name[0] == '\0') { /* handle setting attr first */ if (hdf->attr == NULL) { hdf->attr = attr; } else { _merge_attr(hdf->attr, attr); } /* if we're setting ourselves to ourselves... */ if (hdf->value == value) { if (set_node != NULL) *set_node = hdf; return STATUS_OK; } if (hdf->alloc_value) { free(hdf->value); hdf->value = NULL; } if (value == NULL) { hdf->alloc_value = 0; hdf->value = NULL; } else if (dup) { hdf->alloc_value = 1; hdf->value = strdup(value); if (hdf->value == NULL) return nerr_raise (NERR_NOMEM, "Unable to duplicate value %s for %s", value, name); } else { hdf->alloc_value = wf; hdf->value = (char *)value; } if (set_node != NULL) *set_node = hdf; return STATUS_OK; } n = name; s = strchr (n, '.'); x = (s != NULL) ? s - n : strlen(n); if (x == 0) { return nerr_raise(NERR_ASSERT, "Unable to set Empty component %s", name); } if (hdf->link) { char *new_name = (char *) malloc(strlen(hdf->value) + 1 + strlen(name) + 1); if (new_name == NULL) { return nerr_raise(NERR_NOMEM, "Unable to allocate memory"); } strcpy(new_name, hdf->value); strcat(new_name, "."); strcat(new_name, name); err = _set_value (hdf->top, new_name, value, dup, wf, link, attr, set_node); free(new_name); return nerr_pass(err); } else { hn = hdf; } while (1) { /* examine cache to see if we have a match */ count = 0; hp = hn->last_hp; hs = hn->last_hs; if ((hs == NULL && hp == hn->child) || (hs && hs->next == hp)) { if (hp && hp->name && (x == hp->name_len) && !strncmp (hp->name, n, x)) { goto skip_search; } } hp = hn->child; hs = NULL; /* Look for a matching node at this level */ if (hn->hash != NULL) { hash_key.name = (char *)n; hash_key.name_len = x; hp = ne_hash_lookup(hn->hash, &hash_key); hs = hn->last_child; } else { while (hp != NULL) { if (hp->name && (x == hp->name_len) && !strncmp(hp->name, n, x)) { break; } hs = hp; hp = hp->next; count++; } } /* save in cache any value we found */ if (hp) { hn->last_hp = hp; hn->last_hs = hs; } skip_search: if (hp == NULL) { /* If there was no matching node at this level, we need to * allocate an intersitial node (or the actual node if we're * at the last part of the HDF name) */ if (s != NULL) { /* intersitial */ err = _alloc_hdf (&hp, n, x, NULL, 0, 0, hdf->top); } else { err = _alloc_hdf (&hp, n, x, value, dup, wf, hdf->top); if (link) hp->link = 1; else hp->link = 0; hp->attr = attr; } if (err != STATUS_OK) return nerr_pass (err); if (hn->child == NULL) hn->child = hp; else hs->next = hp; hn->last_child = hp; /* This is the point at which we convert to a hash table * at this level, if we're over the count */ if (count > FORCE_HASH_AT && hn->hash == NULL) { err = _hdf_hash_level(hn); if (err) return nerr_pass(err); } else if (hn->hash != NULL) { err = ne_hash_insert(hn->hash, hp, hp); if (err) return nerr_pass(err); } } else if (s == NULL) { /* If there is a matching node and we're at the end of the HDF * name, then we update the value of the node */ /* handle setting attr first */ if (hp->attr == NULL) { hp->attr = attr; } else { _merge_attr(hp->attr, attr); } if (hp->value != value) { if (hp->alloc_value) { free(hp->value); hp->value = NULL; } if (value == NULL) { hp->alloc_value = 0; hp->value = NULL; } else if (dup) { hp->alloc_value = 1; hp->value = strdup(value); if (hp->value == NULL) return nerr_raise (NERR_NOMEM, "Unable to duplicate value %s for %s", value, name); } else { hp->alloc_value = wf; hp->value = (char *)value; } } if (link) hp->link = 1; else hp->link = 0; } else if (hp->link) { char *new_name = (char *) malloc(strlen(hp->value) + strlen(s) + 1); if (new_name == NULL) { return nerr_raise(NERR_NOMEM, "Unable to allocate memory"); } strcpy(new_name, hp->value); strcat(new_name, s); err = _set_value (hdf->top, new_name, value, dup, wf, link, attr, set_node); free(new_name); return nerr_pass(err); } /* At this point, we're done if there is not more HDF name space to * traverse */ if (s == NULL) break; /* Otherwise, we need to find the next part of the namespace */ n = s + 1; s = strchr (n, '.'); x = (s != NULL) ? s - n : strlen(n); if (x == 0) { return nerr_raise(NERR_ASSERT, "Unable to set Empty component %s", name); } hn = hp; } if (set_node != NULL) *set_node = hp; return STATUS_OK; } NEOERR* hdf_set_value (HDF *hdf, const char *name, const char *value) { return nerr_pass(_set_value (hdf, name, value, 1, 1, 0, NULL, NULL)); } NEOERR* hdf_set_value_attr (HDF *hdf, const char *name, const char *value, HDF_ATTR *attr) { return nerr_pass(_set_value (hdf, name, value, 1, 1, 0, attr, NULL)); } NEOERR* hdf_set_symlink (HDF *hdf, const char *src, const char *dest) { return nerr_pass(_set_value (hdf, src, dest, 1, 1, 1, NULL, NULL)); } NEOERR* hdf_set_int_value (HDF *hdf, const char *name, int value) { char buf[256]; snprintf (buf, sizeof(buf), "%d", value); return nerr_pass(_set_value (hdf, name, buf, 1, 1, 0, NULL, NULL)); } NEOERR* hdf_set_buf (HDF *hdf, const char *name, char *value) { return nerr_pass(_set_value (hdf, name, value, 0, 1, 0, NULL, NULL)); } NEOERR* hdf_set_copy (HDF *hdf, const char *dest, const char *src) { HDF *node; if ((_walk_hdf(hdf, src, &node) == 0) && (node->value != NULL)) { return nerr_pass(_set_value (hdf, dest, node->value, 0, 0, 0, NULL, NULL)); } return nerr_raise (NERR_NOT_FOUND, "Unable to find %s", src); } NEOERR* hdf_set_valuevf (HDF *hdf, const char *fmt, va_list ap) { NEOERR *err; char *k; char *v; k = vsprintf_alloc(fmt, ap); if (k == NULL) { return nerr_raise(NERR_NOMEM, "Unable to allocate memory for format string"); } v = strchr(k, '='); if (v == NULL) { err = nerr_raise(NERR_ASSERT, "No equals found: %s", k); free(k); return err; } *v++ = '\0'; err = hdf_set_value(hdf, k, v); free(k); return nerr_pass(err); } NEOERR* hdf_set_valuef (HDF *hdf, const char *fmt, ...) { NEOERR *err; va_list ap; va_start(ap, fmt); err = hdf_set_valuevf(hdf, fmt, ap); va_end(ap); return nerr_pass(err); } NEOERR* hdf_get_node (HDF *hdf, const char *name, HDF **ret) { _walk_hdf(hdf, name, ret); if (*ret == NULL) { return nerr_pass(_set_value (hdf, name, NULL, 0, 1, 0, NULL, ret)); } return STATUS_OK; } /* Ok, this version avoids the bubble sort by walking the level once to * load them all into a ULIST, qsort'ing the list, and then dumping them * back out... */ NEOERR *hdf_sort_obj (HDF *h, int (*compareFunc)(const void *, const void *)) { NEOERR *err = STATUS_OK; ULIST *level = NULL; HDF *p, *c; int x; if (h == NULL) return STATUS_OK; c = h->child; if (c == NULL) return STATUS_OK; do { err = uListInit(&level, 40, 0); if (err) return nerr_pass(err); for (p = c; p; p = p->next) { err = uListAppend(level, p); if (err) break; } err = uListSort(level, compareFunc); if (err) break; uListGet(level, 0, (void *)&c); h->child = c; for (x = 1; x < uListLength(level); x++) { uListGet(level, x, (void *)&p); c->next = p; p->next = NULL; c = p; } h->last_child = c; } while (0); uListDestroy(&level, 0); return nerr_pass(err); } NEOERR* hdf_remove_tree (HDF *hdf, const char *name) { HDF *hp = hdf; HDF *lp = NULL, *ln = NULL; /* last parent, last node */ int x = 0; const char *s = name; const char *n = name; if (hdf == NULL) return STATUS_OK; hp = hdf->child; if (hp == NULL) { return STATUS_OK; } lp = hdf; ln = NULL; n = name; s = strchr (n, '.'); x = (s == NULL) ? strlen(n) : s - n; while (1) { while (hp != NULL) { if (hp->name && (x == hp->name_len) && !strncmp(hp->name, n, x)) { break; } else { ln = hp; hp = hp->next; } } if (hp == NULL) { return STATUS_OK; } if (s == NULL) break; lp = hp; ln = NULL; hp = hp->child; n = s + 1; s = strchr (n, '.'); x = (s == NULL) ? strlen(n) : s - n; } if (lp->hash != NULL) { ne_hash_remove(lp->hash, hp); } if (ln) { ln->next = hp->next; /* check to see if we are the last parent's last_child, if so * repoint so hash table inserts will go to the right place */ if (hp == lp->last_child) lp->last_child = ln; hp->next = NULL; } else { lp->child = hp->next; hp->next = NULL; } _dealloc_hdf (&hp); return STATUS_OK; } static NEOERR * _copy_attr (HDF_ATTR **dest, HDF_ATTR *src) { HDF_ATTR *copy, *last = NULL; *dest = NULL; while (src != NULL) { copy = (HDF_ATTR *)malloc(sizeof(HDF_ATTR)); if (copy == NULL) { _dealloc_hdf_attr(dest); return nerr_raise(NERR_NOMEM, "Unable to allocate copy of HDF_ATTR"); } copy->key = strdup(src->key); copy->value = strdup(src->value); copy->next = NULL; if ((copy->key == NULL) || (copy->value == NULL)) { _dealloc_hdf_attr(dest); return nerr_raise(NERR_NOMEM, "Unable to allocate copy of HDF_ATTR"); } if (last) { last->next = copy; } else { *dest = copy; } last = copy; src = src->next; } return STATUS_OK; } static NEOERR * _copy_nodes (HDF *dest, HDF *src) { NEOERR *err = STATUS_OK; HDF *dt, *st; HDF_ATTR *attr_copy; st = src->child; while (st != NULL) { err = _copy_attr(&attr_copy, st->attr); if (err) return nerr_pass(err); err = _set_value(dest, st->name, st->value, 1, 1, 0, attr_copy, &dt); if (err) { _dealloc_hdf_attr(&attr_copy); return nerr_pass(err); } if (src->child) { err = _copy_nodes (dt, st); if (err) return nerr_pass(err); } st = st->next; } return STATUS_OK; } NEOERR* hdf_copy (HDF *dest, const char *name, HDF *src) { NEOERR *err; HDF *node; if (_walk_hdf(dest, name, &node) == -1) { err = _set_value (dest, name, NULL, 0, 0, 0, NULL, &node); if (err) return nerr_pass (err); } return nerr_pass (_copy_nodes (node, src)); } /* BUG: currently, this only prints something if there is a value... * but we now allow attributes on nodes with no value... */ static void gen_ml_break(char *ml, size_t len) { int nlen; int x = 0; ml[x++] = '\n'; nlen = 2 + neo_rand(len-5); if (nlen == 0) { nlen = len / 2; } while (nlen) { ml[x++] = ('A' + neo_rand(26)); nlen--; } ml[x++] = '\n'; ml[x] = '\0'; } typedef NEOERR *(*DUMPF_CB)(void *rock, const char *fmt, ...); static NEOERR *_fp_dump_cb (void *rock, const char *fmt, ...) { FILE *fp = (FILE *)rock; va_list ap; va_start (ap, fmt); vfprintf(fp, fmt, ap); va_end(ap); return STATUS_OK; } static NEOERR *_string_dump_cb (void *rock, const char *fmt, ...) { NEOERR *err; STRING *str = (STRING *)rock; va_list ap; va_start (ap, fmt); err = string_appendvf(str, fmt, ap); va_end(ap); return nerr_pass(err); } #define DUMP_TYPE_DOTTED 0 #define DUMP_TYPE_COMPACT 1 #define DUMP_TYPE_PRETTY 2 static NEOERR* hdf_dump_cb(HDF *hdf, const char *prefix, int dtype, int lvl, void *rock, DUMPF_CB dump_cbf) { NEOERR *err; char *p, op; char ml[10] = "\nEOM\n"; int ml_len = strlen(ml); char whsp[256] = ""; if (dtype == DUMP_TYPE_PRETTY) { memset(whsp, ' ', 256); if (lvl > 127) lvl = 127; whsp[lvl*2] = '\0'; } if (hdf != NULL) hdf = hdf->child; while (hdf != NULL) { op = '='; if (hdf->value) { if (hdf->link) op = ':'; if (prefix && (dtype == DUMP_TYPE_DOTTED)) { err = dump_cbf(rock, "%s.%s", prefix, hdf->name); } else { err = dump_cbf(rock, "%s%s", whsp, hdf->name); } if (err) return nerr_pass (err); if (hdf->attr) { HDF_ATTR *attr = hdf->attr; char *v = NULL; err = dump_cbf(rock, " ["); if (err) return nerr_pass(err); while (attr != NULL) { if (attr->value == NULL || !strcmp(attr->value, "1")) err = dump_cbf(rock, "%s", attr->key); else { v = repr_string_alloc(attr->value); if (v == NULL) return nerr_raise(NERR_NOMEM, "Unable to repr attr %s value %s", attr->key, attr->value); err = dump_cbf(rock, "%s=%s", attr->key, v); free(v); } if (err) return nerr_pass(err); if (attr->next) { err = dump_cbf(rock, ", "); if (err) return nerr_pass(err); } attr = attr->next; } err = dump_cbf(rock, "] "); if (err) return nerr_pass(err); } if (strchr (hdf->value, '\n')) { int vlen = strlen(hdf->value); while (strstr(hdf->value, ml) || ((vlen > ml_len) && !strncmp(hdf->value + vlen - ml_len + 1, ml, strlen(ml) - 1))) { gen_ml_break(ml, sizeof(ml)); ml_len = strlen(ml); } if (hdf->value[strlen(hdf->value)-1] != '\n') err = dump_cbf(rock, " << %s%s%s", ml+1, hdf->value, ml); else err = dump_cbf(rock, " << %s%s%s", ml+1, hdf->value, ml+1); } else { err = dump_cbf(rock, " %c %s\n", op, hdf->value); } if (err) return nerr_pass (err); } if (hdf->child) { if (prefix && (dtype == DUMP_TYPE_DOTTED)) { p = (char *) malloc (strlen(hdf->name) + strlen(prefix) + 2); sprintf (p, "%s.%s", prefix, hdf->name); err = hdf_dump_cb (hdf, p, dtype, lvl+1, rock, dump_cbf); free(p); } else { if (hdf->name && (dtype != DUMP_TYPE_DOTTED)) { err = dump_cbf(rock, "%s%s {\n", whsp, hdf->name); if (err) return nerr_pass (err); err = hdf_dump_cb (hdf, hdf->name, dtype, lvl+1, rock, dump_cbf); if (err) return nerr_pass (err); err = dump_cbf(rock, "%s}\n", whsp); } else { err = hdf_dump_cb (hdf, hdf->name, dtype, lvl+1, rock, dump_cbf); } } if (err) return nerr_pass (err); } hdf = hdf->next; } return STATUS_OK; } NEOERR* hdf_dump_str (HDF *hdf, const char *prefix, int dtype, STRING *str) { return nerr_pass(hdf_dump_cb(hdf, prefix, dtype, 0, str, _string_dump_cb)); } NEOERR* hdf_dump(HDF *hdf, const char *prefix) { return nerr_pass(hdf_dump_cb(hdf, prefix, DUMP_TYPE_DOTTED, 0, stdout, _fp_dump_cb)); } NEOERR* hdf_dump_format (HDF *hdf, int lvl, FILE *fp) { return nerr_pass(hdf_dump_cb(hdf, "", DUMP_TYPE_PRETTY, 0, fp, _fp_dump_cb)); } NEOERR *hdf_write_file (HDF *hdf, const char *path) { NEOERR *err; FILE *fp; fp = fopen(path, "w"); if (fp == NULL) return nerr_raise_errno (NERR_IO, "Unable to open %s for writing", path); err = hdf_dump_format (hdf, 0, fp); fclose (fp); if (err) { unlink(path); } return nerr_pass(err); } NEOERR *hdf_write_file_atomic (HDF *hdf, const char *path) { NEOERR *err; FILE *fp; char tpath[_POSIX_PATH_MAX]; static int count = 0; snprintf(tpath, sizeof(tpath), "%s.%5.5f.%d", path, ne_timef(), count++); fp = fopen(tpath, "w"); if (fp == NULL) return nerr_raise_errno (NERR_IO, "Unable to open %s for writing", tpath); err = hdf_dump_format (hdf, 0, fp); fclose (fp); if (err) { unlink(tpath); return nerr_pass(err); } if (rename(tpath, path) == -1) { unlink (tpath); return nerr_raise_errno (NERR_IO, "Unable to rename file %s to %s", tpath, path); } return STATUS_OK; } NEOERR *hdf_write_string (HDF *hdf, char **s) { STRING str; NEOERR *err; *s = NULL; string_init (&str); err = hdf_dump_str (hdf, NULL, 1, &str); if (err) { string_clear (&str); return nerr_pass(err); } if (str.buf == NULL) { *s = strdup(""); if (*s == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate empty string"); } else { *s = str.buf; } return STATUS_OK; } #define SKIPWS(s) while (*s && isspace(*s)) s++; static int _copy_line (const char **s, char *buf, size_t buf_len) { int x = 0; const char *st = *s; while (*st && x < buf_len-1) { buf[x++] = *st; if (*st++ == '\n') break; } buf[x] = '\0'; *s = st; return x; } /* Copy the characters in the file (up to the next newline) into line * and advance s to the next line */ static NEOERR *_copy_line_advance(const char **s, STRING *line) { NEOERR *err; int x = 0; const char *st = *s; const char *nl; nl = strchr(st, '\n'); if (nl == NULL) { x = strlen(st); err = string_appendn(line, st, x); if (err) return nerr_pass(err); *s = st + x; } else { x = nl - st; err = string_appendn(line, st, x); if (err) return nerr_pass(err); *s = nl + 1; } return STATUS_OK; } char *_strndup(const char *s, int len) { int x; char *dup; if (s == NULL) return NULL; dup = (char *) malloc(len+1); if (dup == NULL) return NULL; for (x = 0; x < len && s[x]; x++) { dup[x] = s[x]; } dup[x] = '\0'; dup[len] = '\0'; return dup; } /* attributes are of the form [key1, key2, key3=value, key4="repr"] */ static NEOERR* parse_attr(char **str, HDF_ATTR **attr) { NEOERR *err = STATUS_OK; char *s = *str; char *k, *v; int k_l, v_l; STRING buf; char c; HDF_ATTR *ha, *hal = NULL; *attr = NULL; string_init(&buf); while (*s && *s != ']') { k = s; k_l = 0; v = NULL; v_l = 0; while (*s && isalnum(*s)) s++; k_l = s-k; if (*s == '\0' || k_l == 0) { _dealloc_hdf_attr(attr); return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str); } SKIPWS(s); if (*s == '=') { s++; SKIPWS(s); if (*s == '"') { s++; while (*s && *s != '"') { if (*s == '\\') { if (isdigit(*(s+1))) { s++; c = *s - '0'; if (isdigit(*(s+1))) { s++; c = (c * 8) + (*s - '0'); if (isdigit(*(s+1))) { s++; c = (c * 8) + (*s - '0'); } } } else { s++; if (*s == 'n') c = '\n'; else if (*s == 't') c = '\t'; else if (*s == 'r') c = '\r'; else c = *s; } err = string_append_char(&buf, c); } else { err = string_append_char(&buf, *s); } if (err) { string_clear(&buf); _dealloc_hdf_attr(attr); return nerr_pass(err); } s++; } if (*s == '\0') { _dealloc_hdf_attr(attr); string_clear(&buf); return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str); } s++; v = buf.buf; v_l = buf.len; } else { v = s; while (*s && *s != ' ' && *s != ',' && *s != ']') s++; if (*s == '\0') { _dealloc_hdf_attr(attr); return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str); } v_l = s-v; } } else { v = "1"; } ha = (HDF_ATTR*) calloc (1, sizeof(HDF_ATTR)); if (ha == NULL) { _dealloc_hdf_attr(attr); string_clear(&buf); return nerr_raise(NERR_NOMEM, "Unable to load attributes: %s", s); } if (*attr == NULL) *attr = ha; ha->key = _strndup(k, k_l); if (v) ha->value = _strndup(v, v_l); else ha->value = strdup(""); if (ha->key == NULL || ha->value == NULL) { _dealloc_hdf_attr(attr); string_clear(&buf); return nerr_raise(NERR_NOMEM, "Unable to load attributes: %s", s); } if (hal != NULL) hal->next = ha; hal = ha; string_clear(&buf); SKIPWS(s); if (*s == ',') { s++; SKIPWS(s); } } if (*s == '\0') { _dealloc_hdf_attr(attr); return nerr_raise(NERR_PARSE, "Misformed attribute specification: %s", *str); } *str = s+1; return STATUS_OK; } #define INCLUDE_ERROR 0 #define INCLUDE_IGNORE 1 #define INCLUDE_FILE 2 static NEOERR* _hdf_read_string (HDF *hdf, const char **str, STRING *line, const char *path, int *lineno, int include_handle) { NEOERR *err; HDF *lower; char *s; char *name, *value; HDF_ATTR *attr = NULL; while (**str != '\0') { /* Reset string length, but don't free the reserved buffer */ line->len = 0; err = _copy_line_advance(str, line); if (err) return nerr_pass(err); attr = NULL; (*lineno)++; s = line->buf; SKIPWS(s); if (!strncmp(s, "#include ", 9)) { if (include_handle == INCLUDE_ERROR) { return nerr_raise (NERR_PARSE, "[%d]: #include not supported in string parse", *lineno); } else if (include_handle == INCLUDE_FILE) { int l; s += 9; name = neos_strip(s); l = strlen(name); if (name[0] == '"' && name[l-1] == '"') { name[l-1] = '\0'; name++; } err = hdf_read_file(hdf, name); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } } else if (s[0] == '#') { /* comment: pass */ } else if (s[0] == '}') /* up */ { s = neos_strip(s); if (strcmp(s, "}")) { err = nerr_raise(NERR_PARSE, "[%s:%d] Trailing garbage on line following }: %s", path, *lineno, line->buf); return err; } return STATUS_OK; } else if (s[0]) { /* Valid hdf name is [0-9a-zA-Z_.]+ */ name = s; while (*s && (isalnum(*s) || *s == '_' || *s == '.')) s++; SKIPWS(s); if (s[0] == '[') /* attributes */ { *s = '\0'; name = neos_strip(name); s++; err = parse_attr(&s, &attr); if (err) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } SKIPWS(s); } if (s[0] == '=') /* assignment */ { *s = '\0'; name = neos_strip(name); s++; value = neos_strip(s); err = _set_value (hdf, name, value, 1, 1, 0, attr, NULL); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == ':' && s[1] == '=') /* copy */ { *s = '\0'; name = neos_strip(name); s+=2; value = neos_strip(s); value = hdf_get_value(hdf->top, value, ""); err = _set_value (hdf, name, value, 1, 1, 0, attr, NULL); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == ':') /* link */ { *s = '\0'; name = neos_strip(name); s++; value = neos_strip(s); err = _set_value (hdf, name, value, 1, 1, 1, attr, NULL); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == '{') /* deeper */ { *s = '\0'; name = neos_strip(name); lower = hdf_get_obj (hdf, name); if (lower == NULL) { err = _set_value (hdf, name, NULL, 1, 1, 0, attr, &lower); } else { err = _set_value (lower, NULL, lower->value, 1, 1, 0, attr, NULL); } if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } err = _hdf_read_string (lower, str, line, path, lineno, include_handle); if (err != STATUS_OK) { return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else if (s[0] == '<' && s[1] == '<') /* multi-line assignment */ { char *m; int msize = 0; int mmax = 128; int l; *s = '\0'; name = neos_strip(name); s+=2; value = neos_strip(s); l = strlen(value); if (l == 0) { err = nerr_raise(NERR_PARSE, "[%s:%d] No multi-assignment terminator given: %s", path, *lineno, line->buf); return err; } m = (char *) malloc (mmax * sizeof(char)); if (m == NULL) { return nerr_raise(NERR_NOMEM, "[%s:%d] Unable to allocate memory for multi-line assignment to %s", path, *lineno, name); } while (_copy_line (str, m+msize, mmax-msize) != 0) { (*lineno)++; if (!strncmp(value, m+msize, l) && isspace(m[msize+l])) { m[msize] = '\0'; break; } msize += strlen(m+msize); if (msize + l + 10 > mmax) { mmax += 128; m = (char *) realloc (m, mmax * sizeof(char)); if (m == NULL) { return nerr_raise(NERR_NOMEM, "[%s:%d] Unable to allocate memory for multi-line assignment to %s: size=%d", path, *lineno, name, mmax); } } } err = _set_value (hdf, name, m, 0, 1, 0, attr, NULL); if (err != STATUS_OK) { free (m); return nerr_pass_ctx(err, "In file %s:%d", path, *lineno); } } else { err = nerr_raise(NERR_PARSE, "[%s:%d] Unable to parse line %s", path, *lineno, line->buf); return err; } } } return STATUS_OK; } NEOERR * hdf_read_string (HDF *hdf, const char *str) { NEOERR *err; int lineno = 0; STRING line; string_init(&line); err = _hdf_read_string(hdf, &str, &line, "", &lineno, INCLUDE_ERROR); string_clear(&line); return nerr_pass(err); } NEOERR * hdf_read_string_ignore (HDF *hdf, const char *str, int ignore) { NEOERR *err; int lineno = 0; STRING line; string_init(&line); err = _hdf_read_string(hdf, &str, &line, "", &lineno, (ignore ? INCLUDE_IGNORE : INCLUDE_ERROR)); string_clear(&line); return nerr_pass(err); } /* The search path is part of the HDF by convention */ NEOERR* hdf_search_path (HDF *hdf, const char *path, char *full) { HDF *paths; struct stat s; for (paths = hdf_get_child (hdf, "hdf.loadpaths"); paths; paths = hdf_obj_next (paths)) { snprintf (full, _POSIX_PATH_MAX, "%s/%s", hdf_obj_value(paths), path); errno = 0; if (stat (full, &s) == -1) { if (errno != ENOENT) return nerr_raise_errno (NERR_SYSTEM, "Stat of %s failed", full); } else { return STATUS_OK; } } strncpy (full, path, _POSIX_PATH_MAX); if (stat (full, &s) == -1) { if (errno != ENOENT) return nerr_raise_errno (NERR_SYSTEM, "Stat of %s failed", full); } else return STATUS_OK; return nerr_raise (NERR_NOT_FOUND, "Path %s not found", path); } NEOERR* hdf_read_file (HDF *hdf, const char *path) { NEOERR *err; int lineno = 0; char fpath[_POSIX_PATH_MAX]; char *ibuf = NULL; const char *ptr = NULL; HDF *top = hdf->top; STRING line; string_init(&line); if (path == NULL) return nerr_raise(NERR_ASSERT, "Can't read NULL file"); if (top->fileload) { err = top->fileload(top->fileload_ctx, hdf, path, &ibuf); } else { if (path[0] != '/') { err = hdf_search_path (hdf, path, fpath); if (err != STATUS_OK) return nerr_pass(err); path = fpath; } err = ne_load_file (path, &ibuf); } if (err) return nerr_pass(err); ptr = ibuf; err = _hdf_read_string(hdf, &ptr, &line, path, &lineno, INCLUDE_FILE); free(ibuf); string_clear(&line); return nerr_pass(err); } void hdf_register_fileload(HDF *hdf, void *ctx, HDFFILELOAD fileload) { if (hdf == NULL) return; if (hdf->top != NULL) hdf = hdf->top; hdf->fileload_ctx = ctx; hdf->fileload = fileload; } clearsilver-0.10.5/util/neo_hdf.h0000644001211700116100000005257210645311324013566 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_HDF_H_ #define __NEO_HDF_H_ 1 __BEGIN_DECLS #include #include "util/neo_err.h" #include "util/neo_hash.h" #define FORCE_HASH_AT 10 typedef struct _hdf HDF; /* HDFFILELOAD is a callback function to intercept file load requests and * provide templates via another mechanism. This way you can load templates * that you compiled-into your binary, from in-memory caches, or from a * zip file, etc. The HDF is provided so you can choose to use the * hdf_search_path function to find the file. contents should return * a full malloc copy of the contents of the file, which the parser will * own and free. Use hdf_register_fileload to set this function for * your top level HDF node. * NOTE: Technically, we shouldn't need a separate copy for each parse, but * using the separate copy makes this equivalent to the CSFILELOAD function. We * can change this if we really want to save that copy at the expense of * slightly more complicated code. */ typedef NEOERR* (*HDFFILELOAD)(void *ctx, HDF *hdf, const char *filename, char **contents); typedef struct _attr { char *key; char *value; struct _attr *next; } HDF_ATTR; struct _hdf { int link; int alloc_value; char *name; int name_len; char *value; struct _attr *attr; struct _hdf *top; struct _hdf *next; struct _hdf *child; /* the following fields are used to implement a cache */ struct _hdf *last_hp; struct _hdf *last_hs; /* the following HASH is used when we reach more than FORCE_HASH_AT * elements */ NE_HASH *hash; /* When using the HASH, we need to know where to append new children */ struct _hdf *last_child; /* Should only be set on the head node, used to override the default file * load method */ void *fileload_ctx; HDFFILELOAD fileload; }; /* * Function: hdf_init - Initialize an HDF data set * Description: hdf_init initializes an HDF data set and returns the * pointer to the top node in the data set. * Input: hdf - pointer to an HDF pointer * Output: hdf - allocated hdf node * Returns: NERR_NOMEM - unable to allocate memory for dataset */ NEOERR* hdf_init (HDF **hdf); /* * Function: hdf_destroy - deallocate an HDF data set * Description: hdf_destroy is used to deallocate all memory associated * with an hdf data set. Although you can pass an HDF node * as an argument to this function, you are likely to cause * a segfault if you continue to access the data set. In * the future, we may restrict hdf_destroy so it only works * on the top level node. * Input: hdf - pointer to an HDF data set allocated with hdf_init * Output: None * Returns: None */ void hdf_destroy (HDF **hdf); /* * Function: hdf_get_int_value - Return the integer value of a point in * the data set * Description: hdf_get_int_value walks the HDF data set pointed to by * hdf to name, and returns the value of that node * converted to an integer. If that node does not exist, * or it does not contain a number, the defval is returned. * Input: hdf -> a node in an HDF data set * name -> the name of a node to walk to in the data set * defval -> value to return in case of error or if the node * doesn't exist * Output: None * Returns: The integer value of the node, or the defval */ int hdf_get_int_value (HDF *hdf, const char *name, int defval); /* * Function: hdf_get_value - Return the value of a node in the data set * Description: hdf_get_value walks the data set pointed to by hdf via * name and returns the string value located there, or * defval if the node doesn't exist * Input: hdf -> the dataset node to start from * name -> the name to walk the data set to * defval -> the default value to return if the node doesn't * exist * Output: None * Returns: A pointer to the string stored in the data set, or defval. * The data set maintains ownership of the string, if you want * a copy you either have to call strdup yourself, or use * hdf_get_copy */ char *hdf_get_value (HDF *hdf, const char *name, const char *defval); /* * Function: hdf_get_valuevf - Return the value of a node in the data set * Description: hdf_get_valuevf walks the data set pointed to by hdf via * namefmt printf expanded with varargs ap, and returns the * string value located there, or NULL if it doesn't exist. * This differs from hdf_get_value in that there is no * default value possible. * Input: hdf -> the dataset node to start from * namefmt -> the format string * ap -> va_list of varargs * Output: None * Returns: A pointer to the string stored in the data set, or NULL. * The data set maintains ownership of the string, if you want * a copy you either have to call strdup yourself. */ char* hdf_get_valuevf (HDF *hdf, const char *namefmt, va_list ap); /* * Function: hdf_get_valuef - Return the value of a node in the data set * Description: hdf_get_valuef walks the data set pointed to by hdf via * namefmt printf expanded with varargs, and returns the * string value located there, or NULL if it doesn't exist. * This differs from hdf_get_value in that there is no * default value possible. * Input: hdf -> the dataset node to start from * namefmt -> the printf-style format string * ... -> arguments to fill out namefmt * Output: None * Returns: A pointer to the string stored in the data set, or NULL. * The data set maintains ownership of the string, if you want * a copy you either have to call strdup yourself. */ char* hdf_get_valuef (HDF *hdf, const char *namefmt, ...) ATTRIBUTE_PRINTF(2,3); /* * Function: hdf_get_copy - Returns a copy of a string in the HDF data set * Description: hdf_get_copy is similar to hdf_get_value, except that it * returns an malloc'd copy of the string. * Input: hdf -> the dataset node to start from * name -> the name to walk the data set to * defval -> the default value to return if the node doesn't * exist * Output: value -> the allocated string (if defval = NULL, then value * will be NULL if defval is used) * Returns: NERR_NOMEM if unable to allocate the new copy */ NEOERR* hdf_get_copy (HDF *hdf, const char *name, char **value, const char *defval); /* * Function: hdf_get_obj - return the HDF data set node at a named location * Description: hdf_get_obj walks the dataset given by hdf to the node * named name, and then returns the pointer to that node * Input: hdf -> the dataset node to start from * name -> the name to walk to * Output: None * Returns: the pointer to the named node, or NULL if it doesn't exist */ HDF* hdf_get_obj (HDF *hdf, const char *name); /* * Function: hdf_get_node - Similar to hdf_get_obj except all the nodes * are created if the don't exist. * Description: hdf_get_node is similar to hdf_get_obj, except instead * of stopping if it can't find a node in the tree, it will * create all of the nodes necessary to hand you back the * node you ask for. Nodes are created with no value. * Input: hdf -> the dataset node to start from * name -> the name to walk to * Output: ret -> the dataset node you asked for * Returns: NERR_NOMEM - unable to allocate new nodes */ NEOERR * hdf_get_node (HDF *hdf, const char *name, HDF **ret); /* * Function: hdf_get_child - return the first child of the named node * Description: hdf_get_child will walk the dataset starting at hdf to * name, and return the first child of that node * Input: hdf -> the dataset node to start from * name -> the name to walk to * Output: None * Returns: The first child of the named dataset node or NULL if the * node is not found (or it has no children) */ HDF* hdf_get_child (HDF *hdf, const char *name); /* * Function: hdf_get_attr - * Description: * Input: * Output: * Returns: */ HDF_ATTR* hdf_get_attr (HDF *hdf, const char *name); /* * Function: hdf_set_attr - * Description: * Input: * Output: * Returns: */ NEOERR* hdf_set_attr (HDF *hdf, const char *name, const char *key, const char *value); /* * Function: hdf_obj_child - Return the first child of a dataset node * Description: hdf_obj_child and the other hdf_obj_ functions are * accessors to the HDF dataset. Although we do not * currently "hide" the HDF struct implementation, we * recommend you use the accessor functions instead of * accessing the values directly. * Input: hdf -> the hdf dataset node * Output: None * Returns: The pointer to the first child, or NULL if there is none */ HDF* hdf_obj_child (HDF *hdf); /* * Function: hdf_obj_next - Return the next node of a dataset level * Description: hdf_obj_next is an accessor function for the HDF struct * Input: hdf -> the hdf dataset node * Output: None * Returns: The pointer to the next node, or NULL if there is none */ HDF* hdf_obj_next (HDF *hdf); /* * Function: hdf_obj_top - Return the pointer to the top dataset node * Description: hdf_obj_top is an accessor function which returns a * pointer to the top of the dataset, the node which was * returned by hdf_init. This is most useful for * implementations of language wrappers where individual * nodes are tied garbage colletion wise to the top node of * the data set * Input: hdf -> the hdf dataset node * Output: None * Returns: The pointer to the top node */ HDF* hdf_obj_top (HDF *hdf); /* * Function: hdf_obj_attr - Return the HDF Attributes for a node * Description: * Input: * Output: * Returns: */ HDF_ATTR* hdf_obj_attr (HDF *hdf); /* * Function: hdf_obj_name - Return the name of a node * Description: hdf_obj_name is an accessor function for a datset node * which returns the name of the node. This is just the * local name, and not the full path. * Input: hdf -> the hdf dataset node * Output: None * Returns: The name of the node. If this is the top node, the name is * NULL. */ char* hdf_obj_name (HDF *hdf); /* * Function: hdf_obj_value - Return the value of a node * Description: hdf_obj_value is an accessor function for a dataset node * which returns the value of the node, or NULL if the node * has no value. This is not a copy of the value, so the * node retains ownership of the value * Input: hdf -> the hdf dataset node * Output: None * Returns: The value of the node, or NULL if it has no value */ char* hdf_obj_value (HDF *hdf); /* * Function: hdf_set_value - Set the value of a named node * Description: hdf_set_value will set the value of a named node. All * of the interstitial nodes which don't exist will be * created with a value of NULL. Existing nodes are not * modified. New nodes are created at the end of the list. * If a list of nodes exceeds FORCE_HASH_AT, then a HASH * will be created at that level and all of the nodes will * be added to the hash for faster lookup times. * The copy of the value will be made which the dataset * will own. * Input: hdf -> the pointer to the hdf dataset * name -> the named node to walk to * value -> the value to set the node to * Output: None * Returns: NERR_NOMEM */ NEOERR* hdf_set_value (HDF *hdf, const char *name, const char *value); /* * Function: hdf_set_valuef - Set the value of a named node * Description: hdf_set_valuef is a convenience function that wraps * hdf_set_value. Due to limitations of C, the fmt is in * the format "name=value", where we will first format the * entire string, and then break it at the first (from the * left) equal sign (=) and use the left portion as the * name and the right portion as the value. This function * is somewhat inefficient in that it first allocates the * full name=value, and then the call to hdf_set_value * duplicates the value portion, and then we free the * name=value. * Currently, we don't strip whitespace from the key or * value. In the future, this function might work more * like reading a single line of an HDF string or file, * allowing for attributes and symlinks to be specified... * maybe. * Input: hdf -> the pointer to the hdf dataset * fmt -> the name=value printf(3) format string * Output: None * Returns: NERR_NOMEM */ NEOERR* hdf_set_valuef (HDF *hdf, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); NEOERR* hdf_set_valuevf (HDF *hdf, const char *fmt, va_list ap); /* * Function: hdf_set_int_value - Set the value of a named node to a number * Description: hdf_set_int_value is a helper function that maps an * integer to a string, and then calls hdf_set_value with * that string * Input: hdf -> the pointer to the hdf dataset * name -> the named node to walk to * value -> the value to set the node to * Output: None * Returns: NERR_NOMEM */ NEOERR* hdf_set_int_value (HDF *hdf, const char *name, int value); /* * Function: hdf_set_copy -> Copy a value from one location in the * dataset to another * Description: hdf_set_copy first walks the hdf dataset to the named src * node, and then copies that value to the named dest node. * If the src node is not found, an error is raised. * Input: hdf -> the pointer to the dataset node * dest -> the name of the destination node * src -> the name of the source node * Output: None * Returns: NERR_NOMEM, NERR_NOT_FOUND */ NEOERR* hdf_set_copy (HDF *hdf, const char *dest, const char *src); /* * Function: hdf_set_buf - Set the value of a node without duplicating * the value * Description: hdf_set_buf is similar to hdf_set_value, except the * dataset takes ownership of the value instead of making a * copy of it. The dataset assumes that value was * malloc'd, since it will attempt to free it when * hdf_destroy is called * Input: hdf -> the hdf dataset node * name -> the name to walk to * value -> the malloc'd value * Output: None * Returns: NERR_NOMEM - unable to allocate a node */ NEOERR* hdf_set_buf (HDF *hdf, const char *name, char *value); /* * Function: hdf_set_symlink - Set part of the tree to link to another * Description: hdf_set_symlink creates a link between two sections of * an HDF dataset. The link is "by name" hence the term * "symlink". This means that the destination node does * not need to exist. Any attempt to access the source * node will cause the function to walk to the dest node, * and then continue walking from there. Using symlinks * can "hide" values in the dataset since you won't be able * to access any children of the linked node directly, * though dumps and other things which access the data * structure directly will bypass the symlink. Use this * feature sparingly as its likely to surprise you. * Input: hdf -> the dataset node * src -> the source node name * dest -> the destination node name (from the top of the * dataset, not relative names) * Output: None * Returns: NERR_NOMEM */ NEOERR *hdf_set_symlink (HDF *hdf, const char *src, const char *dest); /* * Function: hdf_sort_obj - sort the children of an HDF node * Description: hdf_sort_obj will sort the children of an HDF node, * based on the given comparison function. * This function works by creating an array of the pointers * for each child object of h, using qsort to sort that * array, and then re-ordering the linked list of children * to the new order. The qsort compare function uses a * pointer to the value in the array, which in our case is * a pointer to an HDF struct, so your comparison function * should work on HDF ** pointers. * Input: h - HDF node * compareFunc - function which returns 1,0,-1 depending on some * criteria. The arguments to this sort function * are pointers to pointers to HDF elements. For * example: * int sortByName(const void *a, const void *b) { * HDF **ha = (HDF **)a; * HDF **hb = (HDF **)b; * * return strcasecmp(hdf_obj_name(*ha), hdf_obj_name(*hb)); * } * * Output: None (h children will be sorted) * Return: NERR_NOMEM */ NEOERR *hdf_sort_obj(HDF *h, int (*compareFunc)(const void *, const void *)); /* * Function: hdf_read_file - read an HDF data file * Description: * Input: * Output: * Returns: NERR_IO, NERR_NOMEM, NERR_PARSE */ NEOERR* hdf_read_file (HDF *hdf, const char *path); /* * Function: hdf_write_file - write an HDF data file * Description: * Input: * Output: * Returns: NERR_IO */ NEOERR* hdf_write_file (HDF *hdf, const char *path); /* * Function: hdf_write_file_atomic - write an HDF data file atomically * Description: hdf_write_file_atomic is similar to hdf_write_file, * except the new file is created with a unique name and * then rename(2) is used to atomically replace the old * file with the new file * Input: * Output: * Returns: NERR_IO */ NEOERR* hdf_write_file_atomic (HDF *hdf, const char *path); /* * Function: hdf_read_string - read an HDF string * Description: * Input: * Output: * Returns: NERR_NOMEM, NERR_PARSE */ NEOERR* hdf_read_string (HDF *hdf, const char *s); /* * Function: hdf_read_string_ignore - Read an HDF string and ignore errors * Description: * Input: * Output: * Returns: NERR_NOMEM */ NEOERR* hdf_read_string_ignore (HDF *hdf, const char *s, int ignore); /* * Function: hdf_write_string - serialize an HDF dataset to a string * Description: * Input: * Output: * Returns: NERR_NOMEM */ NEOERR* hdf_write_string (HDF *hdf, char **s); /* * Function: hdf_dump - dump an HDF dataset to stdout * Description: * Input: * Output: * Returns: */ NEOERR* hdf_dump (HDF *hdf, const char *prefix); /* * Function: hdf_dump_format - dump an HDF dataset to FILE *fp * Description: * Input: * Output: * Returns: */ NEOERR* hdf_dump_format (HDF *hdf, int lvl, FILE *fp); /* * Function: hdf_dump_str - dump an HDF dataset to STRING * Description: * Input: * Output: * Returns: */ NEOERR* hdf_dump_str(HDF *hdf, const char *prefix, int compact, STRING *str); /* * Function: hdf_remove_tree - delete a subtree of an HDF dataset * Description: * Input: * Output: * Returns: */ NEOERR* hdf_remove_tree (HDF *hdf, const char *name); /* * Function: hdf_copy - copy part of an HDF dataset to another * Description: hdf_copy is a deep copy of an HDF tree pointed to by * src to the named node of dest. dest and src need not be * part of the same data set * Input: dest_hdf -> the destination dataset * name -> the name of the destination node * src -> the hdf dataset to copy to the destination * Output: None * Returns: NERR_NOMEM, NERR_NOT_FOUND */ NEOERR* hdf_copy (HDF *dest_hdf, const char *name, HDF *src); /* * Function: hdf_search_path - Find a file given a search path in HDF * Description: hdf_search_path is a convenience/utility function that * searches for relative filenames in a search path. The * search path is the list given by the children of * hdf.loadpaths. * Input: hdf -> the hdf dataset to use * path -> the relative path * full -> a pointer to a _POSIX_PATH_MAX buffer * Output: full -> the full path of the file * Returns: NERR_NOT_FOUND if the file wasn't found in the search path */ NEOERR* hdf_search_path (HDF *hdf, const char *path, char *full); /* * Function: hdf_register_fileload - register a fileload function * Description: hdf_register_fileload registers a fileload function that * overrides the built-in function. The built-in function * uses hdf_search_path and ne_file_load (based on stat/open/read) * to find and load the file on every hdf_read_file (including * #include). You can override this function if you wish to provide * other file search functions, or load the hdf file * from an in-memory cache, etc. * Input: hdf - pointer to a head HDF node * ctx - pointer that is passed to the HDFFILELOAD function when called * fileload - a HDFFILELOAD function * Output: None * Return: None * */ void hdf_register_fileload(HDF *hdf, void *ctx, HDFFILELOAD fileload); __END_DECLS #endif /* __NEO_HDF_H_ */ clearsilver-0.10.5/util/neo_misc.c0000644001211700116100000001373610345210575013755 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" void ne_vwarn (const char *fmt, va_list ap) { char tbuf[20]; char buf[1024]; struct tm my_tm; time_t now; int len; now = time(NULL); localtime_r(&now, &my_tm); strftime(tbuf, sizeof(tbuf), "%m/%d %T", &my_tm); vsnprintf (buf, sizeof(buf), fmt, ap); len = strlen(buf); while (len && isspace (buf[len-1])) buf[--len] = '\0'; fprintf (stderr, "[%s] %s\n", tbuf, buf); } void ne_warn (const char *fmt, ...) { va_list ap; va_start (ap, fmt); ne_vwarn (fmt, ap); va_end (ap); } static int LogLevel = 0; void ne_set_log (int level) { LogLevel = level; } void ne_log (int level, const char *fmt, ...) { va_list ap; if (LogLevel >= level) { va_start (ap, fmt); ne_vwarn (fmt, ap); va_end (ap); } } UINT32 python_string_hash (const char *s) { int len=0; register UINT32 x; x = *s << 7; while(*s != 0) { x = (1000003*x) ^ *s; s++; len++; } x ^= len; if(x == -1) x = -2; return x; } UINT8 *ne_stream4 (UINT8 *dest, UINT32 num) { dest[0] = num & 0xFF; dest[1] = (num >> 8) & 0xFF; dest[2] = (num >> 16) & 0xFF; dest[3] = (num >> 24) & 0xFF; return dest + 4; } UINT8 *ne_stream2 (UINT8 *dest, UINT16 num) { dest[0] = num & 0xFF; dest[1] = (num >> 8) & 0xFF; return dest + 2; } UINT8 *ne_unstream4 (UINT32 *pnum, UINT8 *src) { *pnum = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24); return src + 4; } UINT8 *ne_unstream2 (UINT16 *pnum, UINT8 *src) { *pnum = src[0] | (src[1] << 8); return src + 2; } /* This handles strings of less than 256 bytes */ UINT8 *ne_unstream_str (char *s, int l, UINT8 *src) { UINT8 sl; sl = src[0]; if (sl > l) sl = l; memcpy (s, src+1, sl); s[l-1] = '\0'; return src+sl+1; } UINT8 *ne_stream_str (UINT8 *dest, const char *s, int l) { if (l > 255) { ne_warn("WARNING: calling ne_stream_str with l>255"); l = 255; } dest[0] = l; memcpy (dest+1, s, l); return dest+l+1; } #ifndef HAVE_GETTIMEOFDAY /* Ok, if we don't have gettimeofday, they only get second resolution */ double ne_timef (void) { return time(NULL); } #else double ne_timef (void) { double f = 0; struct timeval tv; int ret; ret = gettimeofday(&tv, NULL); if (ret == 0) { f = tv.tv_sec + (tv.tv_usec / 1000000.0); } return f; } #endif static const UINT32 CRCTable[256] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; UINT32 ne_crc (UINT8 *data, UINT32 bytes) { UINT32 crc, i; crc = (UINT32)-1; for(i = 0; i < bytes; i++, data++) crc = ((crc >> 8) & 0xFFFFFF) ^ CRCTable[((crc ^ *data) & 0xFF)]; crc = ~crc; return crc; } clearsilver-0.10.5/util/neo_misc.h0000644001211700116100000000550110645311660013751 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_MISC_H_ #define __NEO_MISC_H_ 1 #include #include #include /* In case they didn't start from ClearSilver.h. */ #ifndef __CS_CONFIG_H_ #include "cs_config.h" #endif /* Fix Up for systems that don't define these standard things */ #ifndef __BEGIN_DECLS #ifdef __cplusplus #define __BEGIN_DECLS extern "C" { #define __END_DECLS } #else #define __BEGIN_DECLS #define __END_DECLS #endif #endif #ifndef _POSIX_PATH_MAX #define _POSIX_PATH_MAX 255 #endif #ifndef S_IXGRP #define S_IXGRP S_IXUSR #endif #ifndef S_IWGRP #define S_IWGRP S_IWUSR #endif #ifndef S_IRGRP #define S_IRGRP S_IRUSR #endif #ifndef S_IXOTH #define S_IXOTH S_IXUSR #endif #ifndef S_IWOTH #define S_IWOTH S_IWUSR #endif #ifndef S_IROTH #define S_IROTH S_IRUSR #endif /* Format string checking for compilers that support it (GCC style) */ #if __GNUC__ > 2 || __GNUC__ == 2 && __GNUC_MINOR__ > 6 #define ATTRIBUTE_PRINTF(a1,a2) __attribute__((__format__ (__printf__, a1, a2))) #else #define ATTRIBUTE_PRINTF(a1,a2) #endif __BEGIN_DECLS #ifndef HAVE_STRTOK_R char * strtok_r (char *s,const char * delim, char **save_ptr); #endif #ifndef HAVE_LOCALTIME_R struct tm *localtime_r (const time_t *timep, struct tm *ttm); #endif #ifndef HAVE_GMTIME_R struct tm *gmtime_r(const time_t *timep, struct tm *ttm); #endif #ifndef HAVE_MKSTEMP int mkstemp(char *path); #endif #ifndef HAVE_SNPRINTF int snprintf (char *str, size_t count, const char *fmt, ...) ATTRIBUTE_PRINTF(3,4); #endif #ifndef HAVE_VSNPRINTF int vsnprintf (char *str, size_t count, const char *fmt, va_list arg); #endif #include #include typedef unsigned int UINT32; typedef int INT32; typedef unsigned short int UINT16; typedef short int INT16; typedef unsigned char UINT8; typedef char INT8; typedef char BOOL; #ifndef MIN #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif void ne_vwarn (const char *fmt, va_list ap); void ne_warn (const char *fmt, ...) ATTRIBUTE_PRINTF(1,2); void ne_set_log (int level); void ne_log (int level, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); UINT32 python_string_hash (const char *s); UINT8 *ne_stream4 (UINT8 *dest, UINT32 num); UINT8 *ne_unstream4 (UINT32 *pnum, UINT8 *src); UINT8 *ne_stream2 (UINT8 *dest, UINT16 num); UINT8 *ne_unstream2 (UINT16 *pnum, UINT8 *src); UINT8 *ne_stream_str (UINT8 *dest, const char *s, int l); UINT8 *ne_unstream_str (char *s, int l, UINT8 *src); double ne_timef (void); UINT32 ne_crc (UINT8 *data, UINT32 bytes); __END_DECLS #endif /* __NEO_MISC_H_ */ clearsilver-0.10.5/util/neo_net.c0000644001211700116100000003512210345210304013567 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_net.h" #include "neo_str.h" static int ShutdownAccept = 0; void ne_net_shutdown() { ShutdownAccept = 1; } /* Server side */ NEOERR *ne_net_listen(int port, int *fd) { int sfd = 0; int on = 1; /* int flags; */ struct sockaddr_in serv_addr; if ((sfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) return nerr_raise_errno(NERR_IO, "Unable to create socket"); if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to setsockopt(SO_REUSEADDR)"); } if(setsockopt (sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on)) == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to setsockopt(SO_KEEPALIVE)"); } if(setsockopt (sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on)) == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to setsockopt(TCP_NODELAY)"); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(port); if (bind(sfd,(struct sockaddr *)&(serv_addr),sizeof(struct sockaddr)) == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to bind to port %d", port); } /* If set non-block, then we have to use select prior to accept... * typically we don't, so we'll leave this out until we have a need * for it and then figure out how to work it into the common code */ /* flags = fcntl(sfd, F_GETFL, 0 ); if (flags == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to get socket flags for port %d", port); } if (fcntl(sfd, F_SETFL, flags | O_NDELAY) == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY for port %d", port); } */ if (listen(sfd, 100) == -1) { close(sfd); return nerr_raise_errno(NERR_IO, "Unable to listen on port %d", port); } *fd = sfd; return STATUS_OK; } NEOERR *ne_net_accept(NSOCK **sock, int sfd, int data_timeout) { NSOCK *my_sock; int fd; struct sockaddr_in client_addr; socklen_t len; len = sizeof(struct sockaddr_in); while (1) { fd = accept(sfd, (struct sockaddr *)&client_addr, &len); if (fd >= 0) break; if (ShutdownAccept || errno != EINTR) { return nerr_raise_errno(NERR_IO, "accept() returned error"); } if (errno == EINTR) { ne_warn("accept received EINTR"); } } my_sock = (NSOCK *) calloc(1, sizeof(NSOCK)); if (my_sock == NULL) { close(fd); return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NSOCK"); } my_sock->fd = fd; my_sock->remote_ip = ntohl(client_addr.sin_addr.s_addr); my_sock->remote_port = ntohs(client_addr.sin_port); my_sock->data_timeout = data_timeout; *sock = my_sock; return STATUS_OK; } /* Client side */ NEOERR *ne_net_connect(NSOCK **sock, const char *host, int port, int conn_timeout, int data_timeout) { struct sockaddr_in serv_addr; struct hostent hp; struct hostent *php; int fd; int r = 0, x; int flags; struct timeval tv; fd_set fds; int optval; socklen_t optlen; NSOCK *my_sock; /* FIXME: This isn't thread safe... but there's no man entry for the _r * version? */ php = gethostbyname(host); if (php == NULL) { return nerr_raise(NERR_IO, "Host not found: %s", hstrerror(h_errno)); } hp = *php; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) return nerr_raise_errno(NERR_IO, "Unable to create socket"); flags = fcntl(fd, F_GETFL, 0 ); if (flags == -1) { close(fd); return nerr_raise_errno(NERR_IO, "Unable to get socket flags"); } if (fcntl(fd, F_SETFL, flags | O_NDELAY) == -1) { close(fd); return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY"); } x = 0; while (hp.h_addr_list[x] != NULL) { memcpy(&(serv_addr.sin_addr), hp.h_addr_list[x], sizeof(struct in_addr)); errno = 0; r = connect(fd, (struct sockaddr *) &(serv_addr), sizeof(struct sockaddr_in)); if (r == 0 || errno == EINPROGRESS) break; x++; } if (r != 0) { if (errno != EINPROGRESS) { close(fd); return nerr_raise_errno(NERR_IO, "Unable to connect to %s:%d", host, port); } tv.tv_sec = conn_timeout; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(fd, &fds); r = select(fd+1, NULL, &fds, NULL, &tv); if (r == 0) { close(fd); return nerr_raise(NERR_IO, "Connection to %s:%d failed: Timeout", host, port); } if (r < 0) { close(fd); return nerr_raise_errno(NERR_IO, "Connection to %s:%d failed", host, port); } optlen = sizeof(optval); if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &optval, &optlen) == -1) { close(fd); return nerr_raise_errno(NERR_IO, "Unable to getsockopt to determine connection error"); } if (optval) { close(fd); errno = optval; return nerr_raise_errno(NERR_IO, "Connection to %s:%d failed", host, port); } } /* Re-enable blocking... we'll use select on read/write for timeouts * anyways, and if we want non-blocking version in the future we'll * add a flag or something. */ flags = fcntl(fd, F_GETFL, 0 ); if (flags == -1) { close(fd); return nerr_raise_errno(NERR_IO, "Unable to get socket flags"); } if (fcntl(fd, F_SETFL, flags & ~O_NDELAY) == -1) { close(fd); return nerr_raise_errno(NERR_IO, "Unable to set O_NDELAY"); } my_sock = (NSOCK *) calloc(1, sizeof(NSOCK)); if (my_sock == NULL) { close(fd); return nerr_raise(NERR_NOMEM, "Unable to allocate memory for NSOCK"); } my_sock->fd = fd; my_sock->remote_ip = ntohl(serv_addr.sin_addr.s_addr); my_sock->remote_port = port; my_sock->data_timeout = data_timeout; my_sock->conn_timeout = conn_timeout; *sock = my_sock; return STATUS_OK; } NEOERR *ne_net_close(NSOCK **sock) { NEOERR *err; if (sock == NULL || *sock == NULL) return STATUS_OK; err = ne_net_flush(*sock); close((*sock)->fd); free((*sock)); *sock = NULL; return nerr_pass(err); } /* Low level data interface ... we are implementing a buffered stream * here, and the fill and flush are designed for that. More over, our * buffered stream assumes a certain type of protocol design where we * flush the write buffer before reading... there are possible protocols * where this would be grossly inefficient, but I don't expect to use * anything like that */ /* Also, an annoyance here... what to do with the EOF case? Currently, * we're just returing with a ol of 0, which means in most cases when * calling this we have to check that case as well as standard errors. * We could raise an NERR_EOF or something, but that seems like * overkill. We should probably have a ret arg for the case... */ static NEOERR *ne_net_fill(NSOCK *sock) { NEOERR *err; struct timeval tv; fd_set fds; int r; /* Ok, we are assuming a model where one side of the connection is the * consumer and the other the producer... and then it switches. So we * flush the output buffer (if any) before we read */ if (sock->ol) { err = ne_net_flush(sock); if (err) return nerr_pass(err); } /* Ok, we want connections to fail if they don't connect in * conn_timeout... but with higher listen queues, the connection could * actually connect, but the remote server won't get to it within the * conn_timeout, we still want it to fail. We do that by using the * conn_timeout on the first read ... this isn't quite the same as we * might actually timeout at almost 2x conn_timeout (if we had to wait * for connect and the first read) but its still better then waiting * the full data timeout */ if (sock->conn_timeout) { tv.tv_sec = sock->conn_timeout; sock->conn_timeout = 0; } else { tv.tv_sec = sock->data_timeout; } tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(sock->fd, &fds); r = select(sock->fd+1, &fds, NULL, NULL, &tv); if (r == 0) { return nerr_raise(NERR_IO, "read failed: Timeout"); } if (r < 0) { return nerr_raise_errno(NERR_IO, "select for read failed"); } sock->ibuf[0] = '\0'; r = read(sock->fd, sock->ibuf, NET_BUFSIZE); if (r < 0) { return nerr_raise_errno(NERR_IO, "read failed"); } sock->ib = 0; sock->il = r; return STATUS_OK; } NEOERR *ne_net_flush(NSOCK *sock) { fd_set fds; struct timeval tv; int r; int x = 0; if (sock->conn_timeout) { tv.tv_sec = sock->conn_timeout; } else { tv.tv_sec = sock->data_timeout; } tv.tv_usec = 0; x = 0; while (x < sock->ol) { FD_ZERO(&fds); FD_SET(sock->fd, &fds); r = select(sock->fd+1, NULL, &fds, NULL, &tv); if (r == 0) { return nerr_raise(NERR_IO, "write failed: Timeout"); } if (r < 0) { return nerr_raise_errno(NERR_IO, "select for write failed"); } r = write(sock->fd, sock->obuf + x, sock->ol - x); if (r < 0) { return nerr_raise_errno(NERR_IO, "select for write failed"); } x += r; } sock->ol = 0; return STATUS_OK; } /* hmm, we may need something to know how much we've read here... */ NEOERR *ne_net_read(NSOCK *sock, UINT8 *buf, int buflen) { NEOERR *err; int x = 0; int l; x = buflen; while (x > 0) { if (sock->il - sock->ib > 0) { if (sock->ib + x <= sock->il) l = x; else l = sock->il - sock->ib; memcpy(buf + buflen - x, sock->ibuf + sock->ib, l); sock->ib += l; x -= l; } else { err = ne_net_fill(sock); if (err) return nerr_pass(err); if (sock->il == 0) return STATUS_OK; } } return STATUS_OK; } NEOERR *ne_net_read_line(NSOCK *sock, char **buf) { NEOERR *err; STRING str; UINT8 *nl; int l; string_init(&str); while (1) { if (sock->il - sock->ib > 0) { nl = memchr(sock->ibuf + sock->ib, '\n', sock->il - sock->ib); if (nl == NULL) { l = sock->il - sock->ib; err = string_appendn(&str, (char *)(sock->ibuf + sock->ib), l); sock->ib += l; if (err) break; } else { l = nl - (sock->ibuf + sock->ib); err = string_appendn(&str, (char *)(sock->ibuf + sock->ib), l); sock->ib += l; if (err) break; *buf = str.buf; return STATUS_OK; } } else { err = ne_net_fill(sock); if (err) break; if (sock->il == 0) return STATUS_OK; } } string_clear(&str); return nerr_pass(err); } static NEOERR *_ne_net_read_int(NSOCK *sock, int *i, char end) { NEOERR *err; int x = 0; char buf[32]; char *ep = NULL; while (x < sizeof(buf)) { while (sock->il - sock->ib > 0) { buf[x] = sock->ibuf[sock->ib++]; if (buf[x] == end) break; x++; if (x == sizeof(buf)) break; } if (buf[x] == end) break; err = ne_net_fill(sock); if (err) return nerr_pass(err); if (sock->il == 0) return STATUS_OK; } if (x == sizeof(buf)) return nerr_raise(NERR_PARSE, "Format error on stream, expected '%c'", end); buf[x] = '\0'; *i = strtol(buf, &ep, 10); if (ep && *ep) { return nerr_raise(NERR_PARSE, "Format error on stream, expected number followed by '%c'", end); } return STATUS_OK; } NEOERR *ne_net_read_binary(NSOCK *sock, UINT8 **b, int *blen) { NEOERR *err; UINT8 *data; UINT8 buf[5]; int l; err = _ne_net_read_int(sock, &l, ':'); if (err) return nerr_pass(err); /* Special case to read a NULL */ if (l < 0) { *b = NULL; if (blen != NULL) *blen = l; return STATUS_OK; } data = (UINT8 *) malloc(l + 1); if (data == NULL) { /* We might want to clear the incoming data here... */ return nerr_raise(NERR_NOMEM, "Unable to allocate memory for binary data %d" , l); } err = ne_net_read(sock, data, l); if (err) { free(data); return nerr_pass(err); } /* check for comma separator */ err = ne_net_read(sock, buf, 1); if (err) { free(data); return nerr_pass(err); } if (buf[0] != ',') { free(data); return nerr_raise(NERR_PARSE, "Format error on stream, expected ','"); } *b = data; if (blen != NULL) *blen = l; return STATUS_OK; } NEOERR *ne_net_read_str_alloc(NSOCK *sock, char **s, int *len) { NEOERR *err; int l; /* just use the binary read and null terminate the string... */ err = ne_net_read_binary(sock, (UINT8 **)s, &l); if (err) return nerr_pass(err); if (*s != NULL) { (*s)[l] = '\0'; } if (len != NULL) *len = l; return STATUS_OK; } NEOERR *ne_net_read_int(NSOCK *sock, int *i) { return nerr_pass(_ne_net_read_int(sock, i, ',')); } NEOERR *ne_net_write(NSOCK *sock, const char *b, int blen) { NEOERR *err; int x = 0; int l; x = blen; while (x > 0) { if (sock->ol < NET_BUFSIZE) { if (sock->ol + x <= NET_BUFSIZE) { l = x; } else { l = NET_BUFSIZE - sock->ol; } memcpy(sock->obuf + sock->ol, b + blen - x, l); sock->ol += l; x -= l; } else { err = ne_net_flush(sock); if (err) return nerr_pass(err); } } return STATUS_OK; } NEOERR *ne_net_write_line(NSOCK *sock, const char *s) { NEOERR *err; err = ne_net_write(sock, s, strlen(s)); if (err) return nerr_pass(err); err = ne_net_write(sock, "\n", 1); if (err) return nerr_pass(err); return STATUS_OK; } NEOERR *ne_net_write_binary(NSOCK *sock, const char *b, int blen) { NEOERR *err; char buf[32]; if (b == NULL) blen = -1; snprintf(buf, sizeof(buf), "%d:", blen); err = ne_net_write(sock, buf, strlen(buf)); if (err) return nerr_pass(err); if (blen > 0) { err = ne_net_write(sock, b, blen); if (err) return nerr_pass(err); } err = ne_net_write(sock, ",", 1); if (err) return nerr_pass(err); return STATUS_OK; } NEOERR *ne_net_write_str(NSOCK *sock, const char *s) { NEOERR *err; if (s == NULL) err = ne_net_write_binary(sock, s, -1); else err = ne_net_write_binary(sock, s, strlen(s)); return nerr_pass(err); } NEOERR *ne_net_write_int(NSOCK *sock, int i) { char buf[32]; snprintf(buf, sizeof(buf), "%d,", i); return nerr_pass(ne_net_write(sock, buf, strlen(buf))); } clearsilver-0.10.5/util/neo_net.h0000644001211700116100000000274610345210356013611 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_NET_H_ #define __NEO_NET_H_ 1 __BEGIN_DECLS #define NET_BUFSIZE 4096 typedef struct _neo_sock { int fd; int data_timeout; int conn_timeout; UINT32 remote_ip; int remote_port; /* incoming buffer */ UINT8 ibuf[NET_BUFSIZE]; int ib; int il; /* outbound buffer */ UINT8 obuf[NET_BUFSIZE]; int ol; } NSOCK; NEOERR *ne_net_listen(int port, int *fd); NEOERR *ne_net_accept(NSOCK **sock, int fd, int data_timeout); NEOERR *ne_net_connect(NSOCK **sock, const char *host, int port, int conn_timeout, int data_timeout); NEOERR *ne_net_close(NSOCK **sock); NEOERR *ne_net_read(NSOCK *sock, UINT8 *buf, int buflen); NEOERR *ne_net_read_line(NSOCK *sock, char **buf); NEOERR *ne_net_read_binary(NSOCK *sock, UINT8 **b, int *blen); NEOERR *ne_net_read_str_alloc(NSOCK *sock, char **s, int *len); NEOERR *ne_net_read_int(NSOCK *sock, int *i); NEOERR *ne_net_write(NSOCK *sock, const char *b, int blen); NEOERR *ne_net_write_line(NSOCK *sock, const char *s); NEOERR *ne_net_write_binary(NSOCK *sock, const char *b, int blen); NEOERR *ne_net_write_str(NSOCK *sock, const char *s); NEOERR *ne_net_write_int(NSOCK *sock, int i); NEOERR *ne_net_flush(NSOCK *sock); void ne_net_shutdown(void); __END_DECLS #endif /* __NEO_NET_H_ */ clearsilver-0.10.5/util/neo_rand.c0000644001211700116100000000362310261042052013726 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_rand.h" #include "ulist.h" static int RandomInit = 0; void neo_seed_rand (long int seed) { #ifdef HAVE_DRAND48 srand48(seed); #elif HAVE_RANDOM srandom(seed); #else srand(seed); #endif RandomInit = 1; } int neo_rand (int max) { int r; if (RandomInit == 0) { neo_seed_rand (time(NULL)); } #ifdef HAVE_DRAND48 r = drand48() * max; #elif HAVE_RANDOM r = random() * max; #else r = rand() * max; #endif return r; } int neo_rand_string (char *s, int max) { int size; int x = 0; size = neo_rand(max-1); for (x = 0; x < size; x++) { s[x] = (char)(32 + neo_rand(127-32)); if (s[x] == '/') s[x] = ' '; } s[x] = '\0'; return 0; } static ULIST *Words = NULL; int neo_rand_word (char *s, int max) { NEOERR *err; int x; char *word; if (Words == NULL) { FILE *fp; char buf[256]; err = uListInit(&Words, 40000, 0); if (err) { nerr_log_error(err); return -1; } fp = fopen ("/usr/dict/words", "r"); if (fp == NULL) { fp = fopen ("/usr/share/dict/words", "r"); if (fp == NULL) { ne_warn("Unable to find dict/words file (looked in /usr/dict/words and /usr/share/dict/words)"); return -1; } } while (fgets (buf, sizeof(buf), fp) != NULL) { x = strlen (buf); if (buf[x-1] == '\n') buf[x-1] = '\0'; uListAppend(Words, strdup(buf)); } fclose (fp); } x = neo_rand (uListLength(Words)); uListGet(Words, x, (void *)&word); strncpy (s, word, max); s[max-1] = '\0'; return 0; } clearsilver-0.10.5/util/neo_rand.h0000644001211700116100000000072610261037520013740 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_RAND_H_ #define __NEO_RAND_H_ 1 __BEGIN_DECLS void neo_seed_rand (long int seed); int neo_rand (int max); int neo_rand_string (char *s, int slen); int neo_rand_word (char *s, int slen); __END_DECLS #endif /* __NEO_RAND_H_ */ clearsilver-0.10.5/util/neo_server.c0000644001211700116100000001137410261037520014316 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* Initial version based on multi-proc based server (like apache 1.x) * * Parts are: * 1) server Init * 2) sub-proc start * 3) sub-proc init * 4) sub-proc process request * 5) sub-proc cleanup * 6) server cleanup * * Parts 1 & 6 aren't part of the framework, and at this point, I don't * think I need to worry about 3 & 5 either, but maybe in the future. */ #include "cs_config.h" #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_net.h" #include "ulocks.h" #include "neo_server.h" static NEOERR *nserver_child_loop(NSERVER *server, int num) { NEOERR *err = STATUS_OK, *clean_err; int loop = 0; NSOCK *child_sock; if (server->init_cb) { err = server->init_cb(server->data, num); if (err) return nerr_pass(err); } while (loop++ < server->num_requests) { err = fLock(server->accept_lock); if (err) break; err = ne_net_accept(&child_sock, server->server_fd, server->data_timeout); fUnlock(server->accept_lock); if (err) break; err = server->req_cb(server->data, num, child_sock); if (err) { ne_net_close(&child_sock); } else { err = ne_net_close(&child_sock); } nerr_log_error(err); nerr_ignore(&err); } ne_warn("nserver child loop handled %d connections", loop-1); if (server->clean_cb) { clean_err = server->clean_cb(server->data, num); if (clean_err) { nerr_log_error(clean_err); nerr_ignore(&clean_err); } } return nerr_pass(err); } static void ignore_pipe(void) { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = SIG_IGN; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(SIGPIPE, &sa, NULL); } /* Handle shutdown by accepting a TERM signal and then passing it to our * program group */ static int ShutdownPending = 0; static void sig_term(int sig) { ShutdownPending = 1; ne_net_shutdown(); } static void setup_term(void) { struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = sig_term; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); } NEOERR *nserver_proc_start(NSERVER *server, BOOL debug) { NEOERR *err; if (server->req_cb == NULL) return nerr_raise(NERR_ASSERT, "nserver requires a request callback"); ignore_pipe(); setup_term(); ShutdownPending = 0; err = fFind(&(server->accept_lock), server->lockfile); if (err && nerr_handle(&err, NERR_NOT_FOUND)) { err = fCreate(&(server->accept_lock), server->lockfile); } if (err) return nerr_pass(err); do { err = ne_net_listen(server->port, &(server->server_fd)); if (err) break; if (debug == TRUE) { err = nserver_child_loop(server, 0); break; } else { /* create children and restart them as necessary */ pid_t child; int count, status; for (count = 0; count < server->num_children; count++) { child = fork(); if (child == -1) { err = nerr_raise_errno(NERR_SYSTEM, "Unable to fork child"); break; } if (!child) { err = nserver_child_loop(server, count); if (err) exit(-1); exit(0); } ne_warn("Starting child pid %d", child); } if (count < server->num_children) break; while (!ShutdownPending) { child = wait3(&status, 0, NULL); if (child == -1) { ne_warn("wait3 failed [%d] %s", errno, strerror(errno)); continue; } if (WIFSTOPPED(status)) { ne_warn("pid %d stopped on signal %d", child, WSTOPSIG(status)); continue; } if (WIFEXITED(status)) { /* at some point, we might do something here with the * particular exit value */ ne_warn("pid %d exited, returned %d", child, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { ne_warn("pid %d exited on signal %d", child, WTERMSIG(status)); } count++; child = fork(); if (child == -1) { err = nerr_raise_errno(NERR_SYSTEM, "Unable to fork child"); break; } if (!child) { err = nserver_child_loop(server, count); if (err) exit(-1); exit(0); } ne_warn("Starting child pid %d", child); } /* At some point, we might want to actually maintain information * on our children, and then we can be more specific here in terms * of making sure they all shutdown... for now, fergitaboutit */ if (ShutdownPending) { killpg(0, SIGTERM); } } } while (0); fDestroy(server->accept_lock); return nerr_pass(err); } clearsilver-0.10.5/util/neo_server.h0000644001211700116100000000163710261037520014324 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_SERVER_H_ #define __NEO_SERVER_H_ 1 __BEGIN_DECLS /* hmm, this callback might need a mechanism for telling the child to * end... */ typedef NEOERR *(*NSERVER_REQ_CB)(void *rock, int num, NSOCK *sock); typedef NEOERR *(*NSERVER_CB)(void *rock, int num); typedef struct _nserver { /* callbacks */ NSERVER_CB init_cb; NSERVER_REQ_CB req_cb; NSERVER_CB clean_cb; void *data; int num_children; int num_requests; int port; int conn_timeout; int data_timeout; char lockfile[_POSIX_PATH_MAX]; /* Internal data */ int accept_lock; int server_fd; } NSERVER; NEOERR *nserver_proc_start(NSERVER *server, BOOL debug); __END_DECLS #endif /* __NEO_SERVER_H_ */ clearsilver-0.10.5/util/neo_str.c0000644001211700116100000004361110645301260013620 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_str.h" #include "ulist.h" #ifndef va_copy #ifdef __va_copy # define va_copy(dest,src) __va_copy(dest,src) #else # define va_copy(dest,src) ((dest) = (src)) #endif #endif char *neos_strip (char *s) { int x; x = strlen(s) - 1; while (x>=0 && isspace(s[x])) s[x--] = '\0'; while (*s && isspace(*s)) s++; return s; } char *neos_rstrip (char *s) { int n = strlen (s)-1; while (n >= 0 && isspace(s[n])) { s[n] = '\0'; n--; } return s; } void neos_lower(char *s) { while(*s != 0) { *s = tolower(*s); s++; } } void string_init (STRING *str) { str->buf = NULL; str->len = 0; str->max = 0; } void string_clear (STRING *str) { if (str->buf != NULL) free(str->buf); string_init(str); } static NEOERR* string_check_length (STRING *str, int l) { if (str->buf == NULL) { if (l * 10 > 256) str->max = l * 10; else str->max = 256; str->buf = (char *) malloc (sizeof(char) * str->max); if (str->buf == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate render buf of size %d", str->max); /* ne_warn("Creating string %x at %d (%5.2fK)", str, str->max, (str->max / 1024.0)); */ } else if (str->len + l >= str->max) { do { str->max *= 2; } while (str->len + l >= str->max); str->buf = (char *) realloc (str->buf, sizeof(char) * str->max); if (str->buf == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate STRING buf of size %d", str->max); /* ne_warn("Growing string %x to %d (%5.2fK)", str, str->max, (str->max / 1024.0)); */ } return STATUS_OK; } NEOERR *string_set (STRING *str, const char *buf) { str->len = 0; return nerr_pass (string_append (str, buf)); } NEOERR *string_append (STRING *str, const char *buf) { NEOERR *err; int l; l = strlen(buf); err = string_check_length (str, l); if (err != STATUS_OK) return nerr_pass (err); strcpy(str->buf + str->len, buf); str->len += l; return STATUS_OK; } NEOERR *string_appendn (STRING *str, const char *buf, int l) { NEOERR *err; err = string_check_length (str, l+1); if (err != STATUS_OK) return nerr_pass (err); memcpy(str->buf + str->len, buf, l); str->len += l; str->buf[str->len] = '\0'; return STATUS_OK; } /* this is much more efficient with C99 snprintfs... */ NEOERR *string_appendvf (STRING *str, const char *fmt, va_list ap) { NEOERR *err; char buf[4096]; int bl, size; va_list tmp; va_copy(tmp, ap); /* determine length */ size = sizeof (buf); bl = vsnprintf (buf, size, fmt, tmp); if (bl > -1 && bl < size) return string_appendn (str, buf, bl); /* Handle non-C99 snprintfs (requires extra malloc/free and copy) */ if (bl == -1) { char *a_buf; va_copy(tmp, ap); a_buf = vnsprintf_alloc(size*2, fmt, tmp); if (a_buf == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory for formatted string"); err = string_append(str, a_buf); free(a_buf); return nerr_pass(err); } err = string_check_length (str, bl+1); if (err != STATUS_OK) return nerr_pass (err); va_copy(tmp, ap); vsprintf (str->buf + str->len, fmt, tmp); str->len += bl; str->buf[str->len] = '\0'; return STATUS_OK; } NEOERR *string_appendf (STRING *str, const char *fmt, ...) { NEOERR *err; va_list ap; va_start (ap, fmt); err = string_appendvf (str, fmt, ap); va_end (ap); return nerr_pass(err); } NEOERR *string_append_char (STRING *str, char c) { NEOERR *err; err = string_check_length (str, 1); if (err != STATUS_OK) return nerr_pass (err); str->buf[str->len] = c; str->buf[str->len + 1] = '\0'; str->len += 1; return STATUS_OK; } void string_array_init (STRING_ARRAY *arr) { arr->entries = NULL; arr->count = 0; arr->max = 0; } NEOERR *string_array_split (ULIST **list, char *s, const char *sep, int max) { NEOERR *err; char *p, *n, *f; int sl; int x = 0; if (sep[0] == '\0') return nerr_raise (NERR_ASSERT, "separator must be at least one character"); err = uListInit (list, 10, 0); if (err) return nerr_pass(err); sl = strlen(sep); p = (sl == 1) ? strchr (s, sep[0]) : strstr (s, sep); f = s; while (p != NULL) { if (x >= max) break; *p = '\0'; n = strdup(f); *p = sep[0]; if (n) err = uListAppend (*list, n); else err = nerr_raise(NERR_NOMEM, "Unable to allocate memory to split %s", s); if (err) goto split_err; f = p+sl; p = (sl == 1) ? strchr (f, sep[0]) : strstr (f, sep); x++; } /* Handle remainder */ n = strdup(f); if (n) err = uListAppend (*list, n); else err = nerr_raise(NERR_NOMEM, "Unable to allocate memory to split %s", s); if (err) goto split_err; return STATUS_OK; split_err: uListDestroy(list, ULIST_FREE); return err; } void string_array_clear (STRING_ARRAY *arr) { int x; for (x = 0; x < arr->count; x++) { if (arr->entries[x] != NULL) free (arr->entries[x]); arr->entries[x] = NULL; } free (arr->entries); arr->entries = NULL; arr->count = 0; } /* Mostly used by vprintf_alloc for non-C99 compliant snprintfs, * this is like vsprintf_alloc except it takes a "suggested" size */ int vnisprintf_alloc (char **buf, int start_size, const char *fmt, va_list ap) { int bl, size; va_list tmp; *buf = NULL; size = start_size; *buf = (char *) malloc (size * sizeof(char)); if (*buf == NULL) return 0; while (1) { va_copy(tmp, ap); bl = vsnprintf (*buf, size, fmt, tmp); if (bl > -1 && bl < size) return bl; if (bl > -1) size = bl + 1; else size *= 2; *buf = (char *) realloc (*buf, size * sizeof(char)); if (*buf == NULL) return 0; } } char *vnsprintf_alloc (int start_size, const char *fmt, va_list ap) { char *r; vnisprintf_alloc(&r, start_size, fmt, ap); return r; } /* This works better with a C99 compliant vsnprintf, but should work ok * with versions that return a -1 if it overflows the buffer */ int visprintf_alloc (char **buf, const char *fmt, va_list ap) { char ibuf[4096]; int bl, size; va_list tmp; /* PPC doesn't like you re-using a va_list... and it might not be * supposed to work at all */ va_copy(tmp, ap); size = sizeof (ibuf); bl = vsnprintf (ibuf, sizeof (ibuf), fmt, tmp); if (bl > -1 && bl < size) { *buf = (char *) calloc(bl+1, sizeof(char)); if (*buf == NULL) return 0; strncpy(*buf, ibuf, bl); return bl; } if (bl > -1) size = bl + 1; else size *= 2; return vnisprintf_alloc(buf, size, fmt, ap); } char *vsprintf_alloc (const char *fmt, va_list ap) { char *r; visprintf_alloc(&r, fmt, ap); return r; } /* technically, sprintf's can have null values, so we need to be able to * return a length also like real sprintf */ int isprintf_alloc (char **buf, const char *fmt, ...) { va_list ap; int r; va_start (ap, fmt); r = visprintf_alloc (buf, fmt, ap); va_end (ap); return r; } char *sprintf_alloc (const char *fmt, ...) { va_list ap; char *r; va_start (ap, fmt); r = vsprintf_alloc (fmt, ap); va_end (ap); return r; } /* This is mostly just here for completeness, I doubt anyone would use * this (its more efficient (time-wise) if start_size is bigger than the * resulting string. Its less efficient than sprintf_alloc if we have a * C99 snprintf and it doesn't fit in start_size. * BTW: If you are really worried about the efficiency of these * functions, maybe you shouldn't be using them in the first place... */ char *nsprintf_alloc (int start_size, const char *fmt, ...) { va_list ap; char *r; va_start (ap, fmt); r = vnsprintf_alloc (start_size, fmt, ap); va_end (ap); return r; } BOOL reg_search (const char *re, const char *str) { regex_t search_re; int errcode; char buf[256]; if ((errcode = regcomp(&search_re, re, REG_ICASE | REG_EXTENDED | REG_NOSUB))) { regerror (errcode, &search_re, buf, sizeof(buf)); ne_warn ("Unable to compile regex %s: %s", re, buf); return FALSE; } errcode = regexec (&search_re, str, 0, NULL, 0); regfree (&search_re); if (errcode == 0) return TRUE; return FALSE; } NEOERR *string_readline (STRING *str, FILE *fp) { NEOERR *err; /* minimum size for a readline is 256 above current position */ err = string_check_length (str, str->len + 256); if (err != STATUS_OK) return nerr_pass (err); while (fgets(str->buf + str->len, str->max - str->len, fp) != NULL) { str->len = strlen(str->buf); if (str->buf[str->len-1] == '\n') break; err = string_check_length (str, str->len + 256); if (err != STATUS_OK) return nerr_pass (err); } return STATUS_OK; } NEOERR* neos_escape(UINT8 *buf, int buflen, char esc_char, const char *escape, char **esc) { int nl = 0; int l = 0; int x = 0; char *s; int match = 0; while (l < buflen) { if (buf[l] == esc_char) { nl += 2; } else { x = 0; while (escape[x]) { if (escape[x] == buf[l]) { nl +=2; break; } x++; } } nl++; l++; } s = (char *) malloc (sizeof(char) * (nl + 1)); if (s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to escape %s", buf); nl = 0; l = 0; while (l < buflen) { match = 0; if (buf[l] == esc_char) { match = 1; } else { x = 0; while (escape[x]) { if (escape[x] == buf[l]) { match = 1; break; } x++; } } if (match) { s[nl++] = esc_char; s[nl++] = "0123456789ABCDEF"[buf[l] / 16]; s[nl++] = "0123456789ABCDEF"[buf[l] % 16]; l++; } else { s[nl++] = buf[l++]; } } s[nl] = '\0'; *esc = s; return STATUS_OK; } UINT8 *neos_unescape (UINT8 *s, int buflen, char esc_char) { int i = 0, o = 0; if (s == NULL) return s; while (i < buflen) { if (s[i] == esc_char && (i+2 < buflen) && isxdigit(s[i+1]) && isxdigit(s[i+2])) { UINT8 num; num = (s[i+1] >= 'A') ? ((s[i+1] & 0xdf) - 'A') + 10 : (s[i+1] - '0'); num *= 16; num += (s[i+2] >= 'A') ? ((s[i+2] & 0xdf) - 'A') + 10 : (s[i+2] - '0'); s[o++] = num; i+=3; } else { s[o++] = s[i++]; } } if (i && o) s[o] = '\0'; return s; } char *repr_string_alloc (const char *s) { int l,x,i; int nl = 0; char *rs; if (s == NULL) { return strdup("NULL"); } l = strlen(s); for (x = 0; x < l; x++) { if (isprint(s[x]) && s[x] != '"' && s[x] != '\\') { nl++; } else { if (s[x] == '\n' || s[x] == '\t' || s[x] == '\r' || s[x] == '"' || s[x] == '\\') { nl += 2; } else nl += 4; } } rs = (char *) malloc ((nl+3) * sizeof(char)); if (rs == NULL) return NULL; i = 0; rs[i++] = '"'; for (x = 0; x < l; x++) { if (isprint(s[x]) && s[x] != '"' && s[x] != '\\') { rs[i++] = s[x]; } else { rs[i++] = '\\'; switch (s[x]) { case '\n': rs[i++] = 'n'; break; case '\t': rs[i++] = 't'; break; case '\r': rs[i++] = 'r'; break; case '"': rs[i++] = '"'; break; case '\\': rs[i++] = '\\'; break; default: sprintf(&(rs[i]), "%03o", (s[x] & 0377)); i += 3; break; } } } rs[i++] = '"'; rs[i] = '\0'; return rs; } // List of all characters that must be escaped // List based on http://www.blooberry.com/indexdot/html/topics/urlencoding.htm static char EscapedChars[] = "$&+,/:;=?@ \"<>#%{}|\\^~[]`'"; // Check if a single character needs to be escaped static BOOL is_reserved_char(char c) { int i = 0; if (c < 32 || c > 122) { return TRUE; } else { while (EscapedChars[i]) { if (c == EscapedChars[i]) { return TRUE; } ++i; } } return FALSE; } NEOERR *neos_js_escape (const char *in, char **esc) { int nl = 0; int l = 0; unsigned char *buf = (unsigned char *)in; unsigned char *s; while (buf[l]) { if (buf[l] == '/' || buf[l] == '"' || buf[l] == '\'' || buf[l] == '\\' || buf[l] == '>' || buf[l] == '<' || buf[l] == '&' || buf[l] == ';' || buf[l] < 32) { nl += 3; } nl++; l++; } s = (unsigned char *) malloc (sizeof(unsigned char) * (nl + 1)); if (s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to escape %s", buf); nl = 0; l = 0; while (buf[l]) { if (buf[l] == '/' || buf[l] == '"' || buf[l] == '\'' || buf[l] == '\\' || buf[l] == '>' || buf[l] == '<' || buf[l] == '&' || buf[l] == ';' || buf[l] < 32) { s[nl++] = '\\'; s[nl++] = 'x'; s[nl++] = "0123456789ABCDEF"[(buf[l] >> 4) & 0xF]; s[nl++] = "0123456789ABCDEF"[buf[l] & 0xF]; l++; } else { s[nl++] = buf[l++]; } } s[nl] = '\0'; *esc = (char *)s; return STATUS_OK; } NEOERR *neos_url_escape (const char *in, char **esc, const char *other) { int nl = 0; int l = 0; int x = 0; unsigned char *buf = (unsigned char *)in; unsigned char *uother = (unsigned char *)other; unsigned char *s; int match = 0; while (buf[l]) { if (is_reserved_char(buf[l])) { nl += 2; } else if (uother) { x = 0; while (uother[x]) { if (uother[x] == buf[l]) { nl +=2; break; } x++; } } nl++; l++; } s = (unsigned char *) malloc (sizeof(unsigned char) * (nl + 1)); if (s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to escape %s", buf); nl = 0; l = 0; while (buf[l]) { match = 0; if (buf[l] == ' ') { s[nl++] = '+'; l++; } else { if (is_reserved_char(buf[l])) { match = 1; } else if (uother) { x = 0; while (uother[x]) { if (uother[x] == buf[l]) { match = 1; break; } x++; } } if (match) { s[nl++] = '%'; s[nl++] = "0123456789ABCDEF"[buf[l] / 16]; s[nl++] = "0123456789ABCDEF"[buf[l] % 16]; l++; } else { s[nl++] = buf[l++]; } } } s[nl] = '\0'; *esc = (char *)s; return STATUS_OK; } NEOERR *neos_html_escape (const char *src, int slen, char **out) { NEOERR *err = STATUS_OK; STRING out_s; int x; char *ptr; string_init(&out_s); err = string_append (&out_s, ""); if (err) return nerr_pass (err); *out = NULL; x = 0; while (x < slen) { ptr = strpbrk(src + x, "&<>\"'\r"); if (ptr == NULL || (ptr-src >= slen)) { err = string_appendn (&out_s, src + x, slen-x); x = slen; } else { err = string_appendn (&out_s, src + x, (ptr - src) - x); if (err != STATUS_OK) break; x = ptr - src; if (src[x] == '&') err = string_append (&out_s, "&"); else if (src[x] == '<') err = string_append (&out_s, "<"); else if (src[x] == '>') err = string_append (&out_s, ">"); else if (src[x] == '"') err = string_append (&out_s, """); else if (src[x] == '\'') err = string_append (&out_s, "'"); else if (src[x] != '\r') err = nerr_raise (NERR_ASSERT, "src[x] == '%c'", src[x]); x++; } if (err != STATUS_OK) break; } if (err) { string_clear (&out_s); return nerr_pass (err); } *out = out_s.buf; return STATUS_OK; } char *URL_PROTOCOLS[] = {"http://", "https://", "ftp://", "mailto:"}; NEOERR *neos_url_validate (const char *in, char **esc) { NEOERR *err = STATUS_OK; STRING out_s; int valid = 0; size_t i; size_t inlen; int num_protocols = sizeof(URL_PROTOCOLS) / sizeof(char*); void* slashpos; void* colonpos; inlen = strlen(in); /* * or are allowed by browsers * and ":" is treated as part of the path, while * is an invalid url * and ":" is treated as a scheme separator. * * Hence allow for ":" in the path part of a url (after /) */ slashpos = memchr(in, '/', inlen); if (slashpos == NULL) { i = inlen; } else { i = (size_t)((char*)slashpos - in); } colonpos = memchr(in, ':', i); if (colonpos == NULL) { // no scheme in 'in': so this is a relative url valid = 1; } else { for (i = 0; i < num_protocols; i++) { if ((inlen >= strlen(URL_PROTOCOLS[i])) && strncmp(in, URL_PROTOCOLS[i], strlen(URL_PROTOCOLS[i])) == 0) { // 'in' starts with one of the allowed protocols valid = 1; break; } } } if (valid) return neos_html_escape(in, inlen, esc); // 'in' contains an unsupported scheme, replace with '#' string_init(&out_s); err = string_append (&out_s, "#"); if (err) return nerr_pass (err); *esc = out_s.buf; return STATUS_OK; } NEOERR *neos_var_escape (NEOS_ESCAPE context, const char *in, char **esc) { /* Just dup and return if we do nothing. */ if (context == NEOS_ESCAPE_NONE || context == NEOS_ESCAPE_FUNCTION) { *esc = strdup(in); return STATUS_OK; } /* Now we escape based on context. This is the order of precedence: * url > script > style > html */ if (context & NEOS_ESCAPE_URL) return nerr_pass(neos_url_escape(in, esc, NULL)); else if (context & NEOS_ESCAPE_SCRIPT) return nerr_pass(neos_js_escape(in, esc)); else if (context & NEOS_ESCAPE_HTML) return nerr_pass(neos_html_escape(in, strlen(in), esc)); return nerr_raise(NERR_ASSERT, "unknown escape context supplied: %d", context); } clearsilver-0.10.5/util/neo_str.h0000644001211700116100000000706410645311453013634 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __NEO_STR_H_ #define __NEO_STR_H_ 1 __BEGIN_DECLS #include #include #include "util/neo_misc.h" /* This modifies the string its called with by replacing all the white * space on the end with \0, and returns a pointer to the first * non-white space character in the string */ char *neos_strip (char *s); void neos_lower (char *s); char *sprintf_alloc (const char *fmt, ...) ATTRIBUTE_PRINTF(1,2); char *nsprintf_alloc (int start_size, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); char *vsprintf_alloc (const char *fmt, va_list ap); char *vnsprintf_alloc (int start_size, const char *fmt, va_list ap); /* Versions of the above which actually return a length, necessary if * you expect embedded NULLs */ int vnisprintf_alloc (char **buf, int start_size, const char *fmt, va_list ap); int visprintf_alloc (char **buf, const char *fmt, va_list ap); int isprintf_alloc (char **buf, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); typedef struct _string { char *buf; int len; int max; } STRING; typedef struct _string_array { char **entries; int count; int max; } STRING_ARRAY; /* At some point, we should add the concept of "max len" to these so we * can't get DoS'd by someone sending us a line without an end point, * etc. */ void string_init (STRING *str); NEOERR *string_set (STRING *str, const char *buf); NEOERR *string_append (STRING *str, const char *buf); NEOERR *string_appendn (STRING *str, const char *buf, int l); NEOERR *string_append_char (STRING *str, char c); NEOERR *string_appendf (STRING *str, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); NEOERR *string_appendvf (STRING *str, const char *fmt, va_list ap); NEOERR *string_readline (STRING *str, FILE *fp); void string_clear (STRING *str); /* typedef struct _ulist ULIST; */ #include "util/ulist.h" /* s is not const because we actually temporarily modify the string * during split */ NEOERR *string_array_split (ULIST **list, char *s, const char *sep, int max); BOOL reg_search (const char *re, const char *str); /* NEOS_ESCAPE details the support escape contexts/modes handled * by various NEOS helper methods and reused in CS itself. */ typedef enum { NEOS_ESCAPE_UNDEF = 0, /* Used to force eval-time checking */ NEOS_ESCAPE_NONE = 1<<0, NEOS_ESCAPE_HTML = 1<<1, NEOS_ESCAPE_SCRIPT = 1<<2, NEOS_ESCAPE_URL = 1<<3, NEOS_ESCAPE_FUNCTION = 1<<4 /* Special case used to override the others */ } NEOS_ESCAPE; NEOERR* neos_escape(UINT8 *buf, int buflen, char esc_char, const char *escape, char **esc); UINT8 *neos_unescape (UINT8 *s, int buflen, char esc_char); char *repr_string_alloc (const char *s); /* This is the "super" escape call which will call the proper helper * variable escape function based on the passed in context. */ NEOERR *neos_var_escape (NEOS_ESCAPE context, const char *in, char **esc); /* Generic data escaping helper functions used by neos_contextual_escape * and cs built-ins. */ NEOERR *neos_url_escape (const char *in, char **esc, const char *other); NEOERR *neos_js_escape (const char *in, char **esc); NEOERR *neos_html_escape (const char *src, int slen, char **out); NEOERR *neos_url_validate (const char *in, char **esc); __END_DECLS #endif /* __NEO_STR_H_ */ clearsilver-0.10.5/util/osdep.h0000644001211700116100000000127410261037531013266 00000000000000 #ifndef __OSDEP_H__ #define __OSDEP_H__ 1 #ifdef __WINDOWS_GCC__ #include #include #define __BEGIN_DECLS #define __END_DECLS #define _POSIX_PATH_MAX 255 #define S_IXGRP S_IXUSR #define S_IWGRP S_IWUSR #define S_IRGRP S_IRUSR #define S_IROTH S_IRUSR #define S_IWOTH S_IWUSR #define HAVE_STDARG_H 1 #define HAVE_STRING_H 1 #undef HAVE_GMTOFF int snprintf (char *str, size_t count, const char *fmt, ...); int vsnprintf (char *str, size_t count, const char *fmt, va_list arg); int mkstemp(char *path); #define os_random rand #else // UNIX...... #define os_random random #define HAVE_PTHREAD 1 #endif #endif // __OSDEP_H__ clearsilver-0.10.5/util/rcfs.c0000644001211700116100000001320010261042441013070 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * revision-controlled file system (RCFS) with meta-info storage */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_files.h" #include "util/neo_hdf.h" #include "util/ulocks.h" #include "rcfs.h" NEOERR * rcfs_meta_load (const char *path, HDF **meta) { NEOERR *err; char fpath[_POSIX_PATH_MAX]; HDF *m; snprintf (fpath, sizeof(fpath), "%s,log", path); err = hdf_init (&m); if (err) return nerr_pass (err); err = hdf_read_file (m, fpath); if (err) { hdf_destroy (&m); return nerr_pass (err); } *meta = m; return STATUS_OK; } static NEOERR * _meta_save (const char *path, HDF *meta) { NEOERR *err; char ftmp[_POSIX_PATH_MAX]; char fpath[_POSIX_PATH_MAX]; snprintf (ftmp, sizeof(ftmp), "%s,log.tmp", path); snprintf (fpath, sizeof(fpath), "%s,log", path); err = hdf_write_file (meta, ftmp); if (err) return nerr_pass (err); if (rename (ftmp, fpath) == -1) { unlink (ftmp); return nerr_raise_errno (NERR_IO, "Unable to rename file %s", ftmp); } return STATUS_OK; } NEOERR * rcfs_meta_save (const char *path, HDF *meta) { NEOERR *err; int lock; HDF *m; err = rcfs_lock (path, &lock); if (err) return nerr_pass (err); do { err = rcfs_meta_load (path, &m); if (err) break; err = hdf_copy (m, "Meta", meta); if (err) break; err = _meta_save (path, m); } while (0); rcfs_unlock (lock); return nerr_pass (err); } /* load a specified version of the file, version -1 is latest */ NEOERR * rcfs_load (const char *path, int version, char **data) { NEOERR *err; char fpath[_POSIX_PATH_MAX]; if (version == -1) { HDF *meta, *vers; int x; err = rcfs_meta_load (path, &meta); if (err) return nerr_pass (err); for (vers = hdf_get_child (meta, "Versions"); vers; vers = hdf_obj_next (vers)) { x = atoi (hdf_obj_name (vers)); if (x > version) version = x; } hdf_destroy (&meta); } snprintf (fpath, sizeof (fpath), "%s,%d", path, version); err = ne_load_file (fpath, data); return nerr_pass (err); } NEOERR * rcfs_save (const char *path, const char *data, const char *user, const char *log) { NEOERR *err; HDF *meta = NULL, *vers; char fpath[_POSIX_PATH_MAX]; char buf[256]; int version = 0; int fd; int lock; int x, l, w; err = rcfs_lock (path, &lock); if (err) return nerr_pass (err); do { err = rcfs_meta_load (path, &meta); if (err && nerr_handle (&err, NERR_NOT_FOUND)) { /* new file! */ err = hdf_init (&meta); } if (err) return nerr_pass (err); for (vers = hdf_get_child (meta, "Versions"); vers; vers = hdf_obj_next (vers)) { x = atoi (hdf_obj_name (vers)); if (x > version) version = x; } /* new version */ version++; snprintf (fpath, sizeof (fpath), "%s,%d", path, version); fd = open (fpath, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (fd == -1) { err = nerr_raise_errno (NERR_IO, "Unable to create file %s", fpath); break; } l = strlen(data); w = write (fd, data, l); if (w != l) { err = nerr_raise_errno (NERR_IO, "Unable to write file %s", fpath); close (fd); break; } close (fd); snprintf (buf, sizeof(buf), "Versions.%d.Log", version); err = hdf_set_value (meta, buf, log); if (err) break; snprintf (buf, sizeof(buf), "Versions.%d.User", version); err = hdf_set_value (meta, buf, user); if (err) break; snprintf (buf, sizeof(buf), "Versions.%d.Date", version); err = hdf_set_int_value (meta, buf, ne_timef()); if (err) break; err = _meta_save (path, meta); } while (0); rcfs_unlock (lock); hdf_destroy (&meta); return nerr_pass (err); } NEOERR * rcfs_lock (const char *path, int *lock) { NEOERR *err; char fpath[_POSIX_PATH_MAX]; snprintf (fpath, sizeof (fpath), "%s,lock", path); err = fCreate (lock, fpath); if (err) return nerr_pass (err); err = fLock (*lock); if (err) { fDestroy (*lock); return nerr_pass (err); } return STATUS_OK; } void rcfs_unlock (int lock) { fUnlock (lock); fDestroy (lock); } NEOERR * rcfs_listdir (const char *path, ULIST **list) { NEOERR *err; DIR *dp; ULIST *files; struct dirent *de; int l; char *f; *list = NULL; err = uListInit (&files, 10, 0); if (err) return nerr_pass (err); dp = opendir(path); if (dp == NULL) { uListDestroy(&files, ULIST_FREE); if (errno == ENOENT) return nerr_raise (NERR_NOT_FOUND, "Directory %s doesn't exist", path); return nerr_raise_errno (NERR_IO, "Unable to open directory %s", path); } while ((de = readdir (dp)) != NULL) { l = strlen (de->d_name); if (l>4 && !strcmp (de->d_name+l-4, ",log")) { f = (char *) malloc ((l-3) * sizeof(char)); if (f == NULL) { uListDestroy (&files, ULIST_FREE); closedir(dp); return nerr_raise (NERR_NOMEM, "Unable to allocate memory for filename %s", de->d_name); } strncpy (f, de->d_name, l-4); f[l-4] = '\0'; err = uListAppend (files, f); if (err) { free (f); uListDestroy (&files, ULIST_FREE); closedir(dp); return nerr_pass (err); } } } *list = files; closedir(dp); return STATUS_OK; } clearsilver-0.10.5/util/rcfs.h0000644001211700116100000000174110261042477013115 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * revision-controlled file system (RCFS) with meta-info storage */ #ifndef __RCFS_H_ #define __RCFS_H_ 1 typedef struct _rcfs RCFS; NEOERR * rcfs_init (RCFS **rcfs); NEOERR * rcfs_destroy (RCFS **rcfs); NEOERR * rcfs_load (const char *path, int version, char **data); NEOERR * rcfs_save (const char *path, const char *data, const char *user, const char *log); NEOERR * rcfs_lock (const char *path, int *lock); void rcfs_unlock (int lock); NEOERR * rcfs_meta_load (const char *path, HDF **meta); NEOERR * rcfs_meta_save (const char *path, HDF *meta); NEOERR * rcfs_listdir (const char *path, ULIST **list); NEOERR * rcfs_link (const char *src_path, const char *dest_path); NEOERR * rcfs_unlink (const char *path); #endif /* __RCFS_H_ */ clearsilver-0.10.5/util/regex/0000755001211700116100000000000010645505044013176 500000000000000clearsilver-0.10.5/util/regex/regex.c0000644001211700116100000047223710344026304014404 00000000000000/* Extended regular expression matching and search library, version 0.12. (Implements POSIX draft P10003.2/D11.2, except for internationalization features.) Copyright (C) 1993, 1994, 1995, 1996 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* AIX requires this to be the first thing in the file. */ #if defined (_AIX) && !defined (REGEX_MALLOC) #pragma alloca #endif #undef _GNU_SOURCE #define _GNU_SOURCE #include "cs_config.h" #include "util/osdep.h" #ifdef HAVE_CONFIG_H #include #endif /* We need this for `regex.h', and perhaps for the Emacs include files. */ #include /* This is for other GNU distributions with internationalized messages. */ #if HAVE_LIBINTL_H || defined (_LIBC) # include #else # define gettext(msgid) (msgid) #endif #ifndef gettext_noop /* This define is so xgettext can find the internationalizable strings. */ #define gettext_noop(String) String #endif /* The `emacs' switch turns on certain matching commands that make sense only in Emacs. */ #ifdef emacs #include "lisp.h" #include "buffer.h" #include "syntax.h" #else /* not emacs */ /* If we are not linking with Emacs proper, we can't use the relocating allocator even if config.h says that we can. */ #undef REL_ALLOC #if defined (STDC_HEADERS) || defined (_LIBC) #include #else char *malloc (); char *realloc (); #endif /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow. If nothing else has been done, use the method below. */ #ifdef INHIBIT_STRING_HEADER #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY)) #if !defined (bzero) && !defined (bcopy) #undef INHIBIT_STRING_HEADER #endif #endif #endif /* This is the normal way of making sure we have a bcopy and a bzero. This is used in most programs--a few other programs avoid this by defining INHIBIT_STRING_HEADER. */ #ifndef INHIBIT_STRING_HEADER #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC) #include #ifndef bcmp #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n)) #endif #ifndef bcopy #define bcopy(s, d, n) memcpy ((d), (s), (n)) #endif #ifndef bzero #define bzero(s, n) memset ((s), 0, (n)) #endif #else #include #endif #endif /* Define the syntax stuff for \<, \>, etc. */ /* This must be nonzero for the wordchar and notwordchar pattern commands in re_match_2. */ #ifndef Sword #define Sword 1 #endif #ifdef SWITCH_ENUM_BUG #define SWITCH_ENUM_CAST(x) ((int)(x)) #else #define SWITCH_ENUM_CAST(x) (x) #endif #ifdef SYNTAX_TABLE extern char *re_syntax_table; #else /* not SYNTAX_TABLE */ /* How many characters in the character set. */ #define CHAR_SET_SIZE 256 static char re_syntax_table[CHAR_SET_SIZE]; static void init_syntax_once () { register int c; static int done = 0; if (done) return; bzero (re_syntax_table, sizeof re_syntax_table); for (c = 'a'; c <= 'z'; c++) re_syntax_table[c] = Sword; for (c = 'A'; c <= 'Z'; c++) re_syntax_table[c] = Sword; for (c = '0'; c <= '9'; c++) re_syntax_table[c] = Sword; re_syntax_table['_'] = Sword; done = 1; } #endif /* not SYNTAX_TABLE */ #define SYNTAX(c) re_syntax_table[c] #endif /* not emacs */ /* Get the interface, including the syntax bits. */ #include "regex.h" /* isalpha etc. are used for the character classes. */ #include /* Jim Meyering writes: "... Some ctype macros are valid only for character codes that isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when using /bin/cc or gcc but without giving an ansi option). So, all ctype uses should be through macros like ISPRINT... If STDC_HEADERS is defined, then autoconf has verified that the ctype macros don't need to be guarded with references to isascii. ... Defining IN_CTYPE_DOMAIN to 1 should let any compiler worth its salt eliminate the && through constant folding." */ #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII)) #define IN_CTYPE_DOMAIN(c) 1 #else #define IN_CTYPE_DOMAIN(c) isascii(c) #endif #ifdef isblank #define ISBLANK(c) (IN_CTYPE_DOMAIN (c) && isblank (c)) #else #define ISBLANK(c) ((c) == ' ' || (c) == '\t') #endif #ifdef isgraph #define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isgraph (c)) #else #define ISGRAPH(c) (IN_CTYPE_DOMAIN (c) && isprint (c) && !isspace (c)) #endif #define ISPRINT(c) (IN_CTYPE_DOMAIN (c) && isprint (c)) #define ISDIGIT(c) (IN_CTYPE_DOMAIN (c) && isdigit (c)) #define ISALNUM(c) (IN_CTYPE_DOMAIN (c) && isalnum (c)) #define ISALPHA(c) (IN_CTYPE_DOMAIN (c) && isalpha (c)) #define ISCNTRL(c) (IN_CTYPE_DOMAIN (c) && iscntrl (c)) #define ISLOWER(c) (IN_CTYPE_DOMAIN (c) && islower (c)) #define ISPUNCT(c) (IN_CTYPE_DOMAIN (c) && ispunct (c)) #define ISSPACE(c) (IN_CTYPE_DOMAIN (c) && isspace (c)) #define ISUPPER(c) (IN_CTYPE_DOMAIN (c) && isupper (c)) #define ISXDIGIT(c) (IN_CTYPE_DOMAIN (c) && isxdigit (c)) #ifndef NULL #define NULL (void *)0 #endif /* We remove any previous definition of `SIGN_EXTEND_CHAR', since ours (we hope) works properly with all combinations of machines, compilers, `char' and `unsigned char' argument types. (Per Bothner suggested the basic approach.) */ #undef SIGN_EXTEND_CHAR #if __STDC__ #define SIGN_EXTEND_CHAR(c) ((signed char) (c)) #else /* not __STDC__ */ /* As in Harbison and Steele. */ #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128) #endif /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we use `alloca' instead of `malloc'. This is because using malloc in re_search* or re_match* could cause memory leaks when C-g is used in Emacs; also, malloc is slower and causes storage fragmentation. On the other hand, malloc is more portable, and easier to debug. Because we sometimes use alloca, some routines have to be macros, not functions -- `alloca'-allocated space disappears at the end of the function it is called in. */ #ifdef REGEX_MALLOC #define REGEX_ALLOCATE malloc #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize) #define REGEX_FREE free #else /* not REGEX_MALLOC */ /* Emacs already defines alloca, sometimes. */ #ifndef alloca /* Make alloca work the best possible way. */ #ifdef __GNUC__ #define alloca __builtin_alloca #else /* not __GNUC__ */ #if HAVE_ALLOCA_H #include #else /* not __GNUC__ or HAVE_ALLOCA_H */ #if 0 /* It is a bad idea to declare alloca. We always cast the result. */ #ifndef _AIX /* Already did AIX, up at the top. */ char *alloca (); #endif /* not _AIX */ #endif #endif /* not HAVE_ALLOCA_H */ #endif /* not __GNUC__ */ #endif /* not alloca */ #define REGEX_ALLOCATE alloca /* Assumes a `char *destination' variable. */ #define REGEX_REALLOCATE(source, osize, nsize) \ (destination = (char *) alloca (nsize), \ bcopy (source, destination, osize), \ destination) /* No need to do anything to free, after alloca. */ #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */ #endif /* not REGEX_MALLOC */ /* Define how to allocate the failure stack. */ #if defined (REL_ALLOC) && defined (REGEX_MALLOC) #define REGEX_ALLOCATE_STACK(size) \ r_alloc (&failure_stack_ptr, (size)) #define REGEX_REALLOCATE_STACK(source, osize, nsize) \ r_re_alloc (&failure_stack_ptr, (nsize)) #define REGEX_FREE_STACK(ptr) \ r_alloc_free (&failure_stack_ptr) #else /* not using relocating allocator */ #ifdef REGEX_MALLOC #define REGEX_ALLOCATE_STACK malloc #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize) #define REGEX_FREE_STACK free #else /* not REGEX_MALLOC */ #define REGEX_ALLOCATE_STACK alloca #define REGEX_REALLOCATE_STACK(source, osize, nsize) \ REGEX_REALLOCATE (source, osize, nsize) /* No need to explicitly free anything. */ #define REGEX_FREE_STACK(arg) #endif /* not REGEX_MALLOC */ #endif /* not using relocating allocator */ /* True if `size1' is non-NULL and PTR is pointing anywhere inside `string1' or just past its end. This works if PTR is NULL, which is a good thing. */ #define FIRST_STRING_P(ptr) \ (size1 && string1 <= (ptr) && (ptr) <= string1 + size1) /* (Re)Allocate N items of type T using malloc, or fail. */ #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t))) #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t))) #define RETALLOC_IF(addr, n, t) \ if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t) #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t))) #define BYTEWIDTH 8 /* In bits. */ #define STREQ(s1, s2) ((strcmp (s1, s2) == 0)) #undef MAX #undef MIN #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) typedef char boolean; #define false 0 #define true 1 static int re_match_2_internal (); /* These are the command codes that appear in compiled regular expressions. Some opcodes are followed by argument bytes. A command code can specify any interpretation whatsoever for its arguments. Zero bytes may appear in the compiled regular expression. */ typedef enum { no_op = 0, /* Succeed right away--no more backtracking. */ succeed, /* Followed by one byte giving n, then by n literal bytes. */ exactn, /* Matches any (more or less) character. */ anychar, /* Matches any one char belonging to specified set. First following byte is number of bitmap bytes. Then come bytes for a bitmap saying which chars are in. Bits in each byte are ordered low-bit-first. A character is in the set if its bit is 1. A character too large to have a bit in the map is automatically not in the set. */ charset, /* Same parameters as charset, but match any character that is not one of those specified. */ charset_not, /* Start remembering the text that is matched, for storing in a register. Followed by one byte with the register number, in the range 0 to one less than the pattern buffer's re_nsub field. Then followed by one byte with the number of groups inner to this one. (This last has to be part of the start_memory only because we need it in the on_failure_jump of re_match_2.) */ start_memory, /* Stop remembering the text that is matched and store it in a memory register. Followed by one byte with the register number, in the range 0 to one less than `re_nsub' in the pattern buffer, and one byte with the number of inner groups, just like `start_memory'. (We need the number of inner groups here because we don't have any easy way of finding the corresponding start_memory when we're at a stop_memory.) */ stop_memory, /* Match a duplicate of something remembered. Followed by one byte containing the register number. */ duplicate, /* Fail unless at beginning of line. */ begline, /* Fail unless at end of line. */ endline, /* Succeeds if at beginning of buffer (if emacs) or at beginning of string to be matched (if not). */ begbuf, /* Analogously, for end of buffer/string. */ endbuf, /* Followed by two byte relative address to which to jump. */ jump, /* Same as jump, but marks the end of an alternative. */ jump_past_alt, /* Followed by two-byte relative address of place to resume at in case of failure. */ on_failure_jump, /* Like on_failure_jump, but pushes a placeholder instead of the current string position when executed. */ on_failure_keep_string_jump, /* Throw away latest failure point and then jump to following two-byte relative address. */ pop_failure_jump, /* Change to pop_failure_jump if know won't have to backtrack to match; otherwise change to jump. This is used to jump back to the beginning of a repeat. If what follows this jump clearly won't match what the repeat does, such that we can be sure that there is no use backtracking out of repetitions already matched, then we change it to a pop_failure_jump. Followed by two-byte address. */ maybe_pop_jump, /* Jump to following two-byte address, and push a dummy failure point. This failure point will be thrown away if an attempt is made to use it for a failure. A `+' construct makes this before the first repeat. Also used as an intermediary kind of jump when compiling an alternative. */ dummy_failure_jump, /* Push a dummy failure point and continue. Used at the end of alternatives. */ push_dummy_failure, /* Followed by two-byte relative address and two-byte number n. After matching N times, jump to the address upon failure. */ succeed_n, /* Followed by two-byte relative address, and two-byte number n. Jump to the address N times, then fail. */ jump_n, /* Set the following two-byte relative address to the subsequent two-byte number. The address *includes* the two bytes of number. */ set_number_at, wordchar, /* Matches any word-constituent character. */ notwordchar, /* Matches any char that is not a word-constituent. */ wordbeg, /* Succeeds if at word beginning. */ wordend, /* Succeeds if at word end. */ wordbound, /* Succeeds if at a word boundary. */ notwordbound /* Succeeds if not at a word boundary. */ #ifdef emacs ,before_dot, /* Succeeds if before point. */ at_dot, /* Succeeds if at point. */ after_dot, /* Succeeds if after point. */ /* Matches any character whose syntax is specified. Followed by a byte which contains a syntax code, e.g., Sword. */ syntaxspec, /* Matches any character whose syntax is not that specified. */ notsyntaxspec #endif /* emacs */ } re_opcode_t; /* Common operations on the compiled pattern. */ /* Store NUMBER in two contiguous bytes starting at DESTINATION. */ #define STORE_NUMBER(destination, number) \ do { \ (destination)[0] = (number) & 0377; \ (destination)[1] = (number) >> 8; \ } while (0) /* Same as STORE_NUMBER, except increment DESTINATION to the byte after where the number is stored. Therefore, DESTINATION must be an lvalue. */ #define STORE_NUMBER_AND_INCR(destination, number) \ do { \ STORE_NUMBER (destination, number); \ (destination) += 2; \ } while (0) /* Put into DESTINATION a number stored in two contiguous bytes starting at SOURCE. */ #define EXTRACT_NUMBER(destination, source) \ do { \ (destination) = *(source) & 0377; \ (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \ } while (0) #ifdef DEBUG static void extract_number (dest, source) int *dest; unsigned char *source; { int temp = SIGN_EXTEND_CHAR (*(source + 1)); *dest = *source & 0377; *dest += temp << 8; } #ifndef EXTRACT_MACROS /* To debug the macros. */ #undef EXTRACT_NUMBER #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src) #endif /* not EXTRACT_MACROS */ #endif /* DEBUG */ /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number. SOURCE must be an lvalue. */ #define EXTRACT_NUMBER_AND_INCR(destination, source) \ do { \ EXTRACT_NUMBER (destination, source); \ (source) += 2; \ } while (0) #ifdef DEBUG static void extract_number_and_incr (destination, source) int *destination; unsigned char **source; { extract_number (destination, *source); *source += 2; } #ifndef EXTRACT_MACROS #undef EXTRACT_NUMBER_AND_INCR #define EXTRACT_NUMBER_AND_INCR(dest, src) \ extract_number_and_incr (&dest, &src) #endif /* not EXTRACT_MACROS */ #endif /* DEBUG */ /* If DEBUG is defined, Regex prints many voluminous messages about what it is doing (if the variable `debug' is nonzero). If linked with the main program in `iregex.c', you can enter patterns and strings interactively. And if linked with the main program in `main.c' and the other test files, you can run the already-written tests. */ #ifdef DEBUG /* We use standard I/O for debugging. */ #include /* It is useful to test things that ``must'' be true when debugging. */ #include static int debug = 0; #define DEBUG_STATEMENT(e) e #define DEBUG_PRINT1(x) if (debug) printf (x) #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2) #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3) #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4) #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \ if (debug) print_partial_compiled_pattern (s, e) #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \ if (debug) print_double_string (w, s1, sz1, s2, sz2) /* Print the fastmap in human-readable form. */ void print_fastmap (fastmap) char *fastmap; { unsigned was_a_range = 0; unsigned i = 0; while (i < (1 << BYTEWIDTH)) { if (fastmap[i++]) { was_a_range = 0; putchar (i - 1); while (i < (1 << BYTEWIDTH) && fastmap[i]) { was_a_range = 1; i++; } if (was_a_range) { printf ("-"); putchar (i - 1); } } } putchar ('\n'); } /* Print a compiled pattern string in human-readable form, starting at the START pointer into it and ending just before the pointer END. */ void print_partial_compiled_pattern (start, end) unsigned char *start; unsigned char *end; { int mcnt, mcnt2; unsigned char *p = start; unsigned char *pend = end; if (start == NULL) { printf ("(null)\n"); return; } /* Loop over pattern commands. */ while (p < pend) { printf ("%d:\t", p - start); switch ((re_opcode_t) *p++) { case no_op: printf ("/no_op"); break; case exactn: mcnt = *p++; printf ("/exactn/%d", mcnt); do { putchar ('/'); putchar (*p++); } while (--mcnt); break; case start_memory: mcnt = *p++; printf ("/start_memory/%d/%d", mcnt, *p++); break; case stop_memory: mcnt = *p++; printf ("/stop_memory/%d/%d", mcnt, *p++); break; case duplicate: printf ("/duplicate/%d", *p++); break; case anychar: printf ("/anychar"); break; case charset: case charset_not: { register int c, last = -100; register int in_range = 0; printf ("/charset [%s", (re_opcode_t) *(p - 1) == charset_not ? "^" : ""); assert (p + *p < pend); for (c = 0; c < 256; c++) if (c / 8 < *p && (p[1 + (c/8)] & (1 << (c % 8)))) { /* Are we starting a range? */ if (last + 1 == c && ! in_range) { putchar ('-'); in_range = 1; } /* Have we broken a range? */ else if (last + 1 != c && in_range) { putchar (last); in_range = 0; } if (! in_range) putchar (c); last = c; } if (in_range) putchar (last); putchar (']'); p += 1 + *p; } break; case begline: printf ("/begline"); break; case endline: printf ("/endline"); break; case on_failure_jump: extract_number_and_incr (&mcnt, &p); printf ("/on_failure_jump to %d", p + mcnt - start); break; case on_failure_keep_string_jump: extract_number_and_incr (&mcnt, &p); printf ("/on_failure_keep_string_jump to %d", p + mcnt - start); break; case dummy_failure_jump: extract_number_and_incr (&mcnt, &p); printf ("/dummy_failure_jump to %d", p + mcnt - start); break; case push_dummy_failure: printf ("/push_dummy_failure"); break; case maybe_pop_jump: extract_number_and_incr (&mcnt, &p); printf ("/maybe_pop_jump to %d", p + mcnt - start); break; case pop_failure_jump: extract_number_and_incr (&mcnt, &p); printf ("/pop_failure_jump to %d", p + mcnt - start); break; case jump_past_alt: extract_number_and_incr (&mcnt, &p); printf ("/jump_past_alt to %d", p + mcnt - start); break; case jump: extract_number_and_incr (&mcnt, &p); printf ("/jump to %d", p + mcnt - start); break; case succeed_n: extract_number_and_incr (&mcnt, &p); extract_number_and_incr (&mcnt2, &p); printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2); break; case jump_n: extract_number_and_incr (&mcnt, &p); extract_number_and_incr (&mcnt2, &p); printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2); break; case set_number_at: extract_number_and_incr (&mcnt, &p); extract_number_and_incr (&mcnt2, &p); printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2); break; case wordbound: printf ("/wordbound"); break; case notwordbound: printf ("/notwordbound"); break; case wordbeg: printf ("/wordbeg"); break; case wordend: printf ("/wordend"); #ifdef emacs case before_dot: printf ("/before_dot"); break; case at_dot: printf ("/at_dot"); break; case after_dot: printf ("/after_dot"); break; case syntaxspec: printf ("/syntaxspec"); mcnt = *p++; printf ("/%d", mcnt); break; case notsyntaxspec: printf ("/notsyntaxspec"); mcnt = *p++; printf ("/%d", mcnt); break; #endif /* emacs */ case wordchar: printf ("/wordchar"); break; case notwordchar: printf ("/notwordchar"); break; case begbuf: printf ("/begbuf"); break; case endbuf: printf ("/endbuf"); break; default: printf ("?%d", *(p-1)); } putchar ('\n'); } printf ("%d:\tend of pattern.\n", p - start); } void print_compiled_pattern (bufp) struct re_pattern_buffer *bufp; { unsigned char *buffer = bufp->buffer; print_partial_compiled_pattern (buffer, buffer + bufp->used); printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated); if (bufp->fastmap_accurate && bufp->fastmap) { printf ("fastmap: "); print_fastmap (bufp->fastmap); } printf ("re_nsub: %d\t", bufp->re_nsub); printf ("regs_alloc: %d\t", bufp->regs_allocated); printf ("can_be_null: %d\t", bufp->can_be_null); printf ("newline_anchor: %d\n", bufp->newline_anchor); printf ("no_sub: %d\t", bufp->no_sub); printf ("not_bol: %d\t", bufp->not_bol); printf ("not_eol: %d\t", bufp->not_eol); printf ("syntax: %d\n", bufp->syntax); /* Perhaps we should print the translate table? */ } void print_double_string (where, string1, size1, string2, size2) const char *where; const char *string1; const char *string2; int size1; int size2; { unsigned this_char; if (where == NULL) printf ("(null)"); else { if (FIRST_STRING_P (where)) { for (this_char = where - string1; this_char < size1; this_char++) putchar (string1[this_char]); where = string2; } for (this_char = where - string2; this_char < size2; this_char++) putchar (string2[this_char]); } } #else /* not DEBUG */ #undef assert #define assert(e) #define DEBUG_STATEMENT(e) #define DEBUG_PRINT1(x) #define DEBUG_PRINT2(x1, x2) #define DEBUG_PRINT3(x1, x2, x3) #define DEBUG_PRINT4(x1, x2, x3, x4) #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) #endif /* not DEBUG */ /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can also be assigned to arbitrarily: each pattern buffer stores its own syntax, so it can be changed between regex compilations. */ /* This has no initializer because initialized variables in Emacs become read-only after dumping. */ reg_syntax_t re_syntax_options; /* Specify the precise syntax of regexps for compilation. This provides for compatibility for various utilities which historically have different, incompatible syntaxes. The argument SYNTAX is a bit mask comprised of the various bits defined in regex.h. We return the old syntax. */ reg_syntax_t re_set_syntax (syntax) reg_syntax_t syntax; { reg_syntax_t ret = re_syntax_options; re_syntax_options = syntax; return ret; } /* This table gives an error message for each of the error codes listed in regex.h. Obviously the order here has to be same as there. POSIX doesn't require that we do anything for REG_NOERROR, but why not be nice? */ static const char *re_error_msgid[] = { gettext_noop ("Success"), /* REG_NOERROR */ gettext_noop ("No match"), /* REG_NOMATCH */ gettext_noop ("Invalid regular expression"), /* REG_BADPAT */ gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */ gettext_noop ("Invalid character class name"), /* REG_ECTYPE */ gettext_noop ("Trailing backslash"), /* REG_EESCAPE */ gettext_noop ("Invalid back reference"), /* REG_ESUBREG */ gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */ gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */ gettext_noop ("Unmatched \\{"), /* REG_EBRACE */ gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */ gettext_noop ("Invalid range end"), /* REG_ERANGE */ gettext_noop ("Memory exhausted"), /* REG_ESPACE */ gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */ gettext_noop ("Premature end of regular expression"), /* REG_EEND */ gettext_noop ("Regular expression too big"), /* REG_ESIZE */ gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */ }; /* Avoiding alloca during matching, to placate r_alloc. */ /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the searching and matching functions should not call alloca. On some systems, alloca is implemented in terms of malloc, and if we're using the relocating allocator routines, then malloc could cause a relocation, which might (if the strings being searched are in the ralloc heap) shift the data out from underneath the regexp routines. Here's another reason to avoid allocation: Emacs processes input from X in a signal handler; processing X input may call malloc; if input arrives while a matching routine is calling malloc, then we're scrod. But Emacs can't just block input while calling matching routines; then we don't notice interrupts when they come in. So, Emacs blocks input around all regexp calls except the matching calls, which it leaves unprotected, in the faith that they will not malloc. */ /* Normally, this is fine. */ #define MATCH_MAY_ALLOCATE /* When using GNU C, we are not REALLY using the C alloca, no matter what config.h may say. So don't take precautions for it. */ #ifdef __GNUC__ #undef C_ALLOCA #endif /* The match routines may not allocate if (1) they would do it with malloc and (2) it's not safe for them to use malloc. Note that if REL_ALLOC is defined, matching would not use malloc for the failure stack, but we would still use it for the register vectors; so REL_ALLOC should not affect this. */ #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs) #undef MATCH_MAY_ALLOCATE #endif /* Failure stack declarations and macros; both re_compile_fastmap and re_match_2 use a failure stack. These have to be macros because of REGEX_ALLOCATE_STACK. */ /* Number of failure points for which to initially allocate space when matching. If this number is exceeded, we allocate more space, so it is not a hard limit. */ #ifndef INIT_FAILURE_ALLOC #define INIT_FAILURE_ALLOC 5 #endif /* Roughly the maximum number of failure points on the stack. Would be exactly that if always used MAX_FAILURE_ITEMS items each time we failed. This is a variable only so users of regex can assign to it; we never change it ourselves. */ #if defined (MATCH_MAY_ALLOCATE) /* 4400 was enough to cause a crash on Alpha OSF/1, whose default stack limit is 2mb. */ int re_max_failures = 20000; #else int re_max_failures = 2000; #endif union fail_stack_elt { unsigned char *pointer; int integer; }; typedef union fail_stack_elt fail_stack_elt_t; typedef struct { fail_stack_elt_t *stack; unsigned size; unsigned avail; /* Offset of next open position. */ } fail_stack_type; #define FAIL_STACK_EMPTY() (fail_stack.avail == 0) #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0) #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size) /* Define macros to initialize and free the failure stack. Do `return -2' if the alloc fails. */ #ifdef MATCH_MAY_ALLOCATE #define INIT_FAIL_STACK() \ do { \ fail_stack.stack = (fail_stack_elt_t *) \ REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \ \ if (fail_stack.stack == NULL) \ return -2; \ \ fail_stack.size = INIT_FAILURE_ALLOC; \ fail_stack.avail = 0; \ } while (0) #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack) #else #define INIT_FAIL_STACK() \ do { \ fail_stack.avail = 0; \ } while (0) #define RESET_FAIL_STACK() #endif /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items. Return 1 if succeeds, and 0 if either ran out of memory allocating space for it or it was already too large. REGEX_REALLOCATE_STACK requires `destination' be declared. */ #define DOUBLE_FAIL_STACK(fail_stack) \ ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \ ? 0 \ : ((fail_stack).stack = (fail_stack_elt_t *) \ REGEX_REALLOCATE_STACK ((fail_stack).stack, \ (fail_stack).size * sizeof (fail_stack_elt_t), \ ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \ \ (fail_stack).stack == NULL \ ? 0 \ : ((fail_stack).size <<= 1, \ 1))) /* Push pointer POINTER on FAIL_STACK. Return 1 if was able to do so and 0 if ran out of memory allocating space to do so. */ #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \ ((FAIL_STACK_FULL () \ && !DOUBLE_FAIL_STACK (FAIL_STACK)) \ ? 0 \ : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \ 1)) /* Push a pointer value onto the failure stack. Assumes the variable `fail_stack'. Probably should only be called from within `PUSH_FAILURE_POINT'. */ #define PUSH_FAILURE_POINTER(item) \ fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item) /* This pushes an integer-valued item onto the failure stack. Assumes the variable `fail_stack'. Probably should only be called from within `PUSH_FAILURE_POINT'. */ #define PUSH_FAILURE_INT(item) \ fail_stack.stack[fail_stack.avail++].integer = (item) /* Push a fail_stack_elt_t value onto the failure stack. Assumes the variable `fail_stack'. Probably should only be called from within `PUSH_FAILURE_POINT'. */ #define PUSH_FAILURE_ELT(item) \ fail_stack.stack[fail_stack.avail++] = (item) /* These three POP... operations complement the three PUSH... operations. All assume that `fail_stack' is nonempty. */ #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail] /* Used to omit pushing failure point id's when we're not debugging. */ #ifdef DEBUG #define DEBUG_PUSH PUSH_FAILURE_INT #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT () #else #define DEBUG_PUSH(item) #define DEBUG_POP(item_addr) #endif /* Push the information about the state we will need if we ever fail back to it. Requires variables fail_stack, regstart, regend, reg_info, and num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be declared. Does `return FAILURE_CODE' if runs out of memory. */ #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \ do { \ char *destination; \ /* Must be int, so when we don't save any registers, the arithmetic \ of 0 + -1 isn't done as unsigned. */ \ int this_reg; \ \ DEBUG_STATEMENT (failure_id++); \ DEBUG_STATEMENT (nfailure_points_pushed++); \ DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \ DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\ DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\ \ DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \ DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \ \ /* Ensure we have enough space allocated for what we will push. */ \ while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \ { \ if (!DOUBLE_FAIL_STACK (fail_stack)) \ return failure_code; \ \ DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \ (fail_stack).size); \ DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\ } \ \ /* Push the info, starting with the registers. */ \ DEBUG_PRINT1 ("\n"); \ \ if (1) \ for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \ this_reg++) \ { \ DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \ DEBUG_STATEMENT (num_regs_pushed++); \ \ DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \ PUSH_FAILURE_POINTER (regstart[this_reg]); \ \ DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \ PUSH_FAILURE_POINTER (regend[this_reg]); \ \ DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \ DEBUG_PRINT2 (" match_null=%d", \ REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \ DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \ DEBUG_PRINT2 (" matched_something=%d", \ MATCHED_SOMETHING (reg_info[this_reg])); \ DEBUG_PRINT2 (" ever_matched=%d", \ EVER_MATCHED_SOMETHING (reg_info[this_reg])); \ DEBUG_PRINT1 ("\n"); \ PUSH_FAILURE_ELT (reg_info[this_reg].word); \ } \ \ DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\ PUSH_FAILURE_INT (lowest_active_reg); \ \ DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\ PUSH_FAILURE_INT (highest_active_reg); \ \ DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \ DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \ PUSH_FAILURE_POINTER (pattern_place); \ \ DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \ DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \ size2); \ DEBUG_PRINT1 ("'\n"); \ PUSH_FAILURE_POINTER (string_place); \ \ DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \ DEBUG_PUSH (failure_id); \ } while (0) /* This is the number of items that are pushed and popped on the stack for each register. */ #define NUM_REG_ITEMS 3 /* Individual items aside from the registers. */ #ifdef DEBUG #define NUM_NONREG_ITEMS 5 /* Includes failure point id. */ #else #define NUM_NONREG_ITEMS 4 #endif /* We push at most this many items on the stack. */ /* We used to use (num_regs - 1), which is the number of registers this regexp will save; but that was changed to 5 to avoid stack overflow for a regexp with lots of parens. */ #define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS) /* We actually push this many items. */ #define NUM_FAILURE_ITEMS \ (((0 \ ? 0 : highest_active_reg - lowest_active_reg + 1) \ * NUM_REG_ITEMS) \ + NUM_NONREG_ITEMS) /* How many items can still be added to the stack without overflowing it. */ #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail) /* Pops what PUSH_FAIL_STACK pushes. We restore into the parameters, all of which should be lvalues: STR -- the saved data position. PAT -- the saved pattern position. LOW_REG, HIGH_REG -- the highest and lowest active registers. REGSTART, REGEND -- arrays of string positions. REG_INFO -- array of information about each subexpression. Also assumes the variables `fail_stack' and (if debugging), `bufp', `pend', `string1', `size1', `string2', and `size2'. */ #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\ { \ DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \ int this_reg; \ const unsigned char *string_temp; \ \ assert (!FAIL_STACK_EMPTY ()); \ \ /* Remove failure points and point to how many regs pushed. */ \ DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \ DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \ DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \ \ assert (fail_stack.avail >= NUM_NONREG_ITEMS); \ \ DEBUG_POP (&failure_id); \ DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \ \ /* If the saved string location is NULL, it came from an \ on_failure_keep_string_jump opcode, and we want to throw away the \ saved NULL, thus retaining our current position in the string. */ \ string_temp = POP_FAILURE_POINTER (); \ if (string_temp != NULL) \ str = (const char *) string_temp; \ \ DEBUG_PRINT2 (" Popping string 0x%x: `", str); \ DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \ DEBUG_PRINT1 ("'\n"); \ \ pat = (unsigned char *) POP_FAILURE_POINTER (); \ DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \ DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \ \ /* Restore register info. */ \ high_reg = (unsigned) POP_FAILURE_INT (); \ DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \ \ low_reg = (unsigned) POP_FAILURE_INT (); \ DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \ \ if (1) \ for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \ { \ DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \ \ reg_info[this_reg].word = POP_FAILURE_ELT (); \ DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \ \ regend[this_reg] = (const char *) POP_FAILURE_POINTER (); \ DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \ \ regstart[this_reg] = (const char *) POP_FAILURE_POINTER (); \ DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \ } \ else \ { \ for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \ { \ reg_info[this_reg].word.integer = 0; \ regend[this_reg] = 0; \ regstart[this_reg] = 0; \ } \ highest_active_reg = high_reg; \ } \ \ set_regs_matched_done = 0; \ DEBUG_STATEMENT (nfailure_points_popped++); \ } /* POP_FAILURE_POINT */ /* Structure for per-register (a.k.a. per-group) information. Other register information, such as the starting and ending positions (which are addresses), and the list of inner groups (which is a bits list) are maintained in separate variables. We are making a (strictly speaking) nonportable assumption here: that the compiler will pack our bit fields into something that fits into the type of `word', i.e., is something that fits into one item on the failure stack. */ typedef union { fail_stack_elt_t word; struct { /* This field is one if this group can match the empty string, zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */ #define MATCH_NULL_UNSET_VALUE 3 unsigned match_null_string_p : 2; unsigned is_active : 1; unsigned matched_something : 1; unsigned ever_matched_something : 1; } bits; } register_info_type; #define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p) #define IS_ACTIVE(R) ((R).bits.is_active) #define MATCHED_SOMETHING(R) ((R).bits.matched_something) #define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something) /* Call this when have matched a real character; it sets `matched' flags for the subexpressions which we are currently inside. Also records that those subexprs have matched. */ #define SET_REGS_MATCHED() \ do \ { \ if (!set_regs_matched_done) \ { \ unsigned r; \ set_regs_matched_done = 1; \ for (r = lowest_active_reg; r <= highest_active_reg; r++) \ { \ MATCHED_SOMETHING (reg_info[r]) \ = EVER_MATCHED_SOMETHING (reg_info[r]) \ = 1; \ } \ } \ } \ while (0) /* Registers are set to a sentinel when they haven't yet matched. */ static char reg_unset_dummy; #define REG_UNSET_VALUE (®_unset_dummy) #define REG_UNSET(e) ((e) == REG_UNSET_VALUE) /* Subroutine declarations and macros for regex_compile. */ static void store_op1 (), store_op2 (); static void insert_op1 (), insert_op2 (); static boolean at_begline_loc_p (), at_endline_loc_p (); static boolean group_in_compile_stack (); static reg_errcode_t compile_range (); /* Fetch the next character in the uncompiled pattern---translating it if necessary. Also cast from a signed character in the constant string passed to us by the user to an unsigned char that we can use as an array index (in, e.g., `translate'). */ #ifndef PATFETCH #define PATFETCH(c) \ do {if (p == pend) return REG_EEND; \ c = (unsigned char) *p++; \ if (translate) c = (unsigned char) translate[c]; \ } while (0) #endif /* Fetch the next character in the uncompiled pattern, with no translation. */ #define PATFETCH_RAW(c) \ do {if (p == pend) return REG_EEND; \ c = (unsigned char) *p++; \ } while (0) /* Go backwards one character in the pattern. */ #define PATUNFETCH p-- /* If `translate' is non-null, return translate[D], else just D. We cast the subscript to translate because some data is declared as `char *', to avoid warnings when a string constant is passed. But when we use a character as a subscript we must make it unsigned. */ #ifndef TRANSLATE #define TRANSLATE(d) \ (translate ? (char) translate[(unsigned char) (d)] : (d)) #endif /* Macros for outputting the compiled pattern into `buffer'. */ /* If the buffer isn't allocated when it comes in, use this. */ #define INIT_BUF_SIZE 32 /* Make sure we have at least N more bytes of space in buffer. */ #define GET_BUFFER_SPACE(n) \ while (b - bufp->buffer + (n) > bufp->allocated) \ EXTEND_BUFFER () /* Make sure we have one more byte of buffer space and then add C to it. */ #define BUF_PUSH(c) \ do { \ GET_BUFFER_SPACE (1); \ *b++ = (unsigned char) (c); \ } while (0) /* Ensure we have two more bytes of buffer space and then append C1 and C2. */ #define BUF_PUSH_2(c1, c2) \ do { \ GET_BUFFER_SPACE (2); \ *b++ = (unsigned char) (c1); \ *b++ = (unsigned char) (c2); \ } while (0) /* As with BUF_PUSH_2, except for three bytes. */ #define BUF_PUSH_3(c1, c2, c3) \ do { \ GET_BUFFER_SPACE (3); \ *b++ = (unsigned char) (c1); \ *b++ = (unsigned char) (c2); \ *b++ = (unsigned char) (c3); \ } while (0) /* Store a jump with opcode OP at LOC to location TO. We store a relative address offset by the three bytes the jump itself occupies. */ #define STORE_JUMP(op, loc, to) \ store_op1 (op, loc, (to) - (loc) - 3) /* Likewise, for a two-argument jump. */ #define STORE_JUMP2(op, loc, to, arg) \ store_op2 (op, loc, (to) - (loc) - 3, arg) /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */ #define INSERT_JUMP(op, loc, to) \ insert_op1 (op, loc, (to) - (loc) - 3, b) /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */ #define INSERT_JUMP2(op, loc, to, arg) \ insert_op2 (op, loc, (to) - (loc) - 3, arg, b) /* This is not an arbitrary limit: the arguments which represent offsets into the pattern are two bytes long. So if 2^16 bytes turns out to be too small, many things would have to change. */ #define MAX_BUF_SIZE (1L << 16) /* Extend the buffer by twice its current size via realloc and reset the pointers that pointed into the old block to point to the correct places in the new one. If extending the buffer results in it being larger than MAX_BUF_SIZE, then flag memory exhausted. */ #define EXTEND_BUFFER() \ do { \ unsigned char *old_buffer = bufp->buffer; \ if (bufp->allocated == MAX_BUF_SIZE) \ return REG_ESIZE; \ bufp->allocated <<= 1; \ if (bufp->allocated > MAX_BUF_SIZE) \ bufp->allocated = MAX_BUF_SIZE; \ bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\ if (bufp->buffer == NULL) \ return REG_ESPACE; \ /* If the buffer moved, move all the pointers into it. */ \ if (old_buffer != bufp->buffer) \ { \ b = (b - old_buffer) + bufp->buffer; \ begalt = (begalt - old_buffer) + bufp->buffer; \ if (fixup_alt_jump) \ fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\ if (laststart) \ laststart = (laststart - old_buffer) + bufp->buffer; \ if (pending_exact) \ pending_exact = (pending_exact - old_buffer) + bufp->buffer; \ } \ } while (0) /* Since we have one byte reserved for the register number argument to {start,stop}_memory, the maximum number of groups we can report things about is what fits in that byte. */ #define MAX_REGNUM 255 /* But patterns can have more than `MAX_REGNUM' registers. We just ignore the excess. */ typedef unsigned regnum_t; /* Macros for the compile stack. */ /* Since offsets can go either forwards or backwards, this type needs to be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */ typedef int pattern_offset_t; typedef struct { pattern_offset_t begalt_offset; pattern_offset_t fixup_alt_jump; pattern_offset_t inner_group_offset; pattern_offset_t laststart_offset; regnum_t regnum; } compile_stack_elt_t; typedef struct { compile_stack_elt_t *stack; unsigned size; unsigned avail; /* Offset of next open position. */ } compile_stack_type; #define INIT_COMPILE_STACK_SIZE 32 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0) #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size) /* The next available element. */ #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail]) /* Set the bit for character C in a list. */ #define SET_LIST_BIT(c) \ (b[((unsigned char) (c)) / BYTEWIDTH] \ |= 1 << (((unsigned char) c) % BYTEWIDTH)) /* Get the next unsigned number in the uncompiled pattern. */ #define GET_UNSIGNED_NUMBER(num) \ { if (p != pend) \ { \ PATFETCH (c); \ while (ISDIGIT (c)) \ { \ if (num < 0) \ num = 0; \ num = num * 10 + c - '0'; \ if (p == pend) \ break; \ PATFETCH (c); \ } \ } \ } #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */ #define IS_CHAR_CLASS(string) \ (STREQ (string, "alpha") || STREQ (string, "upper") \ || STREQ (string, "lower") || STREQ (string, "digit") \ || STREQ (string, "alnum") || STREQ (string, "xdigit") \ || STREQ (string, "space") || STREQ (string, "print") \ || STREQ (string, "punct") || STREQ (string, "graph") \ || STREQ (string, "cntrl") || STREQ (string, "blank")) #ifndef MATCH_MAY_ALLOCATE /* If we cannot allocate large objects within re_match_2_internal, we make the fail stack and register vectors global. The fail stack, we grow to the maximum size when a regexp is compiled. The register vectors, we adjust in size each time we compile a regexp, according to the number of registers it needs. */ static fail_stack_type fail_stack; /* Size with which the following vectors are currently allocated. That is so we can make them bigger as needed, but never make them smaller. */ static int regs_allocated_size; static const char ** regstart, ** regend; static const char ** old_regstart, ** old_regend; static const char **best_regstart, **best_regend; static register_info_type *reg_info; static const char **reg_dummy; static register_info_type *reg_info_dummy; /* Make the register vectors big enough for NUM_REGS registers, but don't make them smaller. */ static regex_grow_registers (num_regs) int num_regs; { if (num_regs > regs_allocated_size) { RETALLOC_IF (regstart, num_regs, const char *); RETALLOC_IF (regend, num_regs, const char *); RETALLOC_IF (old_regstart, num_regs, const char *); RETALLOC_IF (old_regend, num_regs, const char *); RETALLOC_IF (best_regstart, num_regs, const char *); RETALLOC_IF (best_regend, num_regs, const char *); RETALLOC_IF (reg_info, num_regs, register_info_type); RETALLOC_IF (reg_dummy, num_regs, const char *); RETALLOC_IF (reg_info_dummy, num_regs, register_info_type); regs_allocated_size = num_regs; } } #endif /* not MATCH_MAY_ALLOCATE */ /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX. Returns one of error codes defined in `regex.h', or zero for success. Assumes the `allocated' (and perhaps `buffer') and `translate' fields are set in BUFP on entry. If it succeeds, results are put in BUFP (if it returns an error, the contents of BUFP are undefined): `buffer' is the compiled pattern; `syntax' is set to SYNTAX; `used' is set to the length of the compiled pattern; `fastmap_accurate' is zero; `re_nsub' is the number of subexpressions in PATTERN; `not_bol' and `not_eol' are zero; The `fastmap' and `newline_anchor' fields are neither examined nor set. */ /* Return, freeing storage we allocated. */ #define FREE_STACK_RETURN(value) \ return (free (compile_stack.stack), value) static reg_errcode_t regex_compile (pattern, size, syntax, bufp) const char *pattern; int size; reg_syntax_t syntax; struct re_pattern_buffer *bufp; { /* We fetch characters from PATTERN here. Even though PATTERN is `char *' (i.e., signed), we declare these variables as unsigned, so they can be reliably used as array indices. */ register unsigned char c, c1; /* A random temporary spot in PATTERN. */ const char *p1; /* Points to the end of the buffer, where we should append. */ register unsigned char *b; /* Keeps track of unclosed groups. */ compile_stack_type compile_stack; /* Points to the current (ending) position in the pattern. */ const char *p = pattern; const char *pend = pattern + size; /* How to translate the characters in the pattern. */ RE_TRANSLATE_TYPE translate = bufp->translate; /* Address of the count-byte of the most recently inserted `exactn' command. This makes it possible to tell if a new exact-match character can be added to that command or if the character requires a new `exactn' command. */ unsigned char *pending_exact = 0; /* Address of start of the most recently finished expression. This tells, e.g., postfix * where to find the start of its operand. Reset at the beginning of groups and alternatives. */ unsigned char *laststart = 0; /* Address of beginning of regexp, or inside of last group. */ unsigned char *begalt; /* Place in the uncompiled pattern (i.e., the {) to which to go back if the interval is invalid. */ const char *beg_interval; /* Address of the place where a forward jump should go to the end of the containing expression. Each alternative of an `or' -- except the last -- ends with a forward jump of this sort. */ unsigned char *fixup_alt_jump = 0; /* Counts open-groups as they are encountered. Remembered for the matching close-group on the compile stack, so the same register number is put in the stop_memory as the start_memory. */ regnum_t regnum = 0; #ifdef DEBUG DEBUG_PRINT1 ("\nCompiling pattern: "); if (debug) { unsigned debug_count; for (debug_count = 0; debug_count < size; debug_count++) putchar (pattern[debug_count]); putchar ('\n'); } #endif /* DEBUG */ /* Initialize the compile stack. */ compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t); if (compile_stack.stack == NULL) return REG_ESPACE; compile_stack.size = INIT_COMPILE_STACK_SIZE; compile_stack.avail = 0; /* Initialize the pattern buffer. */ bufp->syntax = syntax; bufp->fastmap_accurate = 0; bufp->not_bol = bufp->not_eol = 0; /* Set `used' to zero, so that if we return an error, the pattern printer (for debugging) will think there's no pattern. We reset it at the end. */ bufp->used = 0; /* Always count groups, whether or not bufp->no_sub is set. */ bufp->re_nsub = 0; #if !defined (emacs) && !defined (SYNTAX_TABLE) /* Initialize the syntax table. */ init_syntax_once (); #endif if (bufp->allocated == 0) { if (bufp->buffer) { /* If zero allocated, but buffer is non-null, try to realloc enough space. This loses if buffer's address is bogus, but that is the user's responsibility. */ RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char); } else { /* Caller did not allocate a buffer. Do it for them. */ bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char); } if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE); bufp->allocated = INIT_BUF_SIZE; } begalt = b = bufp->buffer; /* Loop through the uncompiled pattern until we're at the end. */ while (p != pend) { PATFETCH (c); switch (c) { case '^': { if ( /* If at start of pattern, it's an operator. */ p == pattern + 1 /* If context independent, it's an operator. */ || syntax & RE_CONTEXT_INDEP_ANCHORS /* Otherwise, depends on what's come before. */ || at_begline_loc_p (pattern, p, syntax)) BUF_PUSH (begline); else goto normal_char; } break; case '$': { if ( /* If at end of pattern, it's an operator. */ p == pend /* If context independent, it's an operator. */ || syntax & RE_CONTEXT_INDEP_ANCHORS /* Otherwise, depends on what's next. */ || at_endline_loc_p (p, pend, syntax)) BUF_PUSH (endline); else goto normal_char; } break; case '+': case '?': if ((syntax & RE_BK_PLUS_QM) || (syntax & RE_LIMITED_OPS)) goto normal_char; handle_plus: case '*': /* If there is no previous pattern... */ if (!laststart) { if (syntax & RE_CONTEXT_INVALID_OPS) FREE_STACK_RETURN (REG_BADRPT); else if (!(syntax & RE_CONTEXT_INDEP_OPS)) goto normal_char; } { /* Are we optimizing this jump? */ boolean keep_string_p = false; /* 1 means zero (many) matches is allowed. */ char zero_times_ok = 0, many_times_ok = 0; /* If there is a sequence of repetition chars, collapse it down to just one (the right one). We can't combine interval operators with these because of, e.g., `a{2}*', which should only match an even number of `a's. */ for (;;) { zero_times_ok |= c != '+'; many_times_ok |= c != '?'; if (p == pend) break; PATFETCH (c); if (c == '*' || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?'))) ; else if (syntax & RE_BK_PLUS_QM && c == '\\') { if (p == pend) FREE_STACK_RETURN (REG_EESCAPE); PATFETCH (c1); if (!(c1 == '+' || c1 == '?')) { PATUNFETCH; PATUNFETCH; break; } c = c1; } else { PATUNFETCH; break; } /* If we get here, we found another repeat character. */ } /* Star, etc. applied to an empty pattern is equivalent to an empty pattern. */ if (!laststart) break; /* Now we know whether or not zero matches is allowed and also whether or not two or more matches is allowed. */ if (many_times_ok) { /* More than one repetition is allowed, so put in at the end a backward relative jump from `b' to before the next jump we're going to put in below (which jumps from laststart to after this jump). But if we are at the `*' in the exact sequence `.*\n', insert an unconditional jump backwards to the ., instead of the beginning of the loop. This way we only push a failure point once, instead of every time through the loop. */ assert (p - 1 > pattern); /* Allocate the space for the jump. */ GET_BUFFER_SPACE (3); /* We know we are not at the first character of the pattern, because laststart was nonzero. And we've already incremented `p', by the way, to be the character after the `*'. Do we have to do something analogous here for null bytes, because of RE_DOT_NOT_NULL? */ if (TRANSLATE (*(p - 2)) == TRANSLATE ('.') && zero_times_ok && p < pend && TRANSLATE (*p) == TRANSLATE ('\n') && !(syntax & RE_DOT_NEWLINE)) { /* We have .*\n. */ STORE_JUMP (jump, b, laststart); keep_string_p = true; } else /* Anything else. */ STORE_JUMP (maybe_pop_jump, b, laststart - 3); /* We've added more stuff to the buffer. */ b += 3; } /* On failure, jump from laststart to b + 3, which will be the end of the buffer after this jump is inserted. */ GET_BUFFER_SPACE (3); INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump : on_failure_jump, laststart, b + 3); pending_exact = 0; b += 3; if (!zero_times_ok) { /* At least one repetition is required, so insert a `dummy_failure_jump' before the initial `on_failure_jump' instruction of the loop. This effects a skip over that instruction the first time we hit that loop. */ GET_BUFFER_SPACE (3); INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6); b += 3; } } break; case '.': laststart = b; BUF_PUSH (anychar); break; case '[': { boolean had_char_class = false; if (p == pend) FREE_STACK_RETURN (REG_EBRACK); /* Ensure that we have enough space to push a charset: the opcode, the length count, and the bitset; 34 bytes in all. */ GET_BUFFER_SPACE (34); laststart = b; /* We test `*p == '^' twice, instead of using an if statement, so we only need one BUF_PUSH. */ BUF_PUSH (*p == '^' ? charset_not : charset); if (*p == '^') p++; /* Remember the first position in the bracket expression. */ p1 = p; /* Push the number of bytes in the bitmap. */ BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH); /* Clear the whole map. */ bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH); /* charset_not matches newline according to a syntax bit. */ if ((re_opcode_t) b[-2] == charset_not && (syntax & RE_HAT_LISTS_NOT_NEWLINE)) SET_LIST_BIT ('\n'); /* Read in characters and ranges, setting map bits. */ for (;;) { if (p == pend) FREE_STACK_RETURN (REG_EBRACK); PATFETCH (c); /* \ might escape characters inside [...] and [^...]. */ if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') { if (p == pend) FREE_STACK_RETURN (REG_EESCAPE); PATFETCH (c1); SET_LIST_BIT (c1); continue; } /* Could be the end of the bracket expression. If it's not (i.e., when the bracket expression is `[]' so far), the ']' character bit gets set way below. */ if (c == ']' && p != p1 + 1) break; /* Look ahead to see if it's a range when the last thing was a character class. */ if (had_char_class && c == '-' && *p != ']') FREE_STACK_RETURN (REG_ERANGE); /* Look ahead to see if it's a range when the last thing was a character: if this is a hyphen not at the beginning or the end of a list, then it's the range operator. */ if (c == '-' && !(p - 2 >= pattern && p[-2] == '[') && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^') && *p != ']') { reg_errcode_t ret = compile_range (&p, pend, translate, syntax, b); if (ret != REG_NOERROR) FREE_STACK_RETURN (ret); } else if (p[0] == '-' && p[1] != ']') { /* This handles ranges made up of characters only. */ reg_errcode_t ret; /* Move past the `-'. */ PATFETCH (c1); ret = compile_range (&p, pend, translate, syntax, b); if (ret != REG_NOERROR) FREE_STACK_RETURN (ret); } /* See if we're at the beginning of a possible character class. */ else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') { /* Leave room for the null. */ char str[CHAR_CLASS_MAX_LENGTH + 1]; PATFETCH (c); c1 = 0; /* If pattern is `[[:'. */ if (p == pend) FREE_STACK_RETURN (REG_EBRACK); for (;;) { PATFETCH (c); if (c == ':' || c == ']' || p == pend || c1 == CHAR_CLASS_MAX_LENGTH) break; str[c1++] = c; } str[c1] = '\0'; /* If isn't a word bracketed by `[:' and:`]': undo the ending character, the letters, and leave the leading `:' and `[' (but set bits for them). */ if (c == ':' && *p == ']') { int ch; boolean is_alnum = STREQ (str, "alnum"); boolean is_alpha = STREQ (str, "alpha"); boolean is_blank = STREQ (str, "blank"); boolean is_cntrl = STREQ (str, "cntrl"); boolean is_digit = STREQ (str, "digit"); boolean is_graph = STREQ (str, "graph"); boolean is_lower = STREQ (str, "lower"); boolean is_print = STREQ (str, "print"); boolean is_punct = STREQ (str, "punct"); boolean is_space = STREQ (str, "space"); boolean is_upper = STREQ (str, "upper"); boolean is_xdigit = STREQ (str, "xdigit"); if (!IS_CHAR_CLASS (str)) FREE_STACK_RETURN (REG_ECTYPE); /* Throw away the ] at the end of the character class. */ PATFETCH (c); if (p == pend) FREE_STACK_RETURN (REG_EBRACK); for (ch = 0; ch < 1 << BYTEWIDTH; ch++) { int translated = TRANSLATE (ch); /* This was split into 3 if's to avoid an arbitrary limit in some compiler. */ if ( (is_alnum && ISALNUM (ch)) || (is_alpha && ISALPHA (ch)) || (is_blank && ISBLANK (ch)) || (is_cntrl && ISCNTRL (ch))) SET_LIST_BIT (translated); if ( (is_digit && ISDIGIT (ch)) || (is_graph && ISGRAPH (ch)) || (is_lower && ISLOWER (ch)) || (is_print && ISPRINT (ch))) SET_LIST_BIT (translated); if ( (is_punct && ISPUNCT (ch)) || (is_space && ISSPACE (ch)) || (is_upper && ISUPPER (ch)) || (is_xdigit && ISXDIGIT (ch))) SET_LIST_BIT (translated); } had_char_class = true; } else { c1++; while (c1--) PATUNFETCH; SET_LIST_BIT ('['); SET_LIST_BIT (':'); had_char_class = false; } } else { had_char_class = false; SET_LIST_BIT (c); } } /* Discard any (non)matching list bytes that are all 0 at the end of the map. Decrease the map-length byte too. */ while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) b[-1]--; b += b[-1]; } break; case '(': if (syntax & RE_NO_BK_PARENS) goto handle_open; else goto normal_char; case ')': if (syntax & RE_NO_BK_PARENS) goto handle_close; else goto normal_char; case '\n': if (syntax & RE_NEWLINE_ALT) goto handle_alt; else goto normal_char; case '|': if (syntax & RE_NO_BK_VBAR) goto handle_alt; else goto normal_char; case '{': if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES) goto handle_interval; else goto normal_char; case '\\': if (p == pend) FREE_STACK_RETURN (REG_EESCAPE); /* Do not translate the character after the \, so that we can distinguish, e.g., \B from \b, even if we normally would translate, e.g., B to b. */ PATFETCH_RAW (c); switch (c) { case '(': if (syntax & RE_NO_BK_PARENS) goto normal_backslash; handle_open: bufp->re_nsub++; regnum++; if (COMPILE_STACK_FULL) { RETALLOC (compile_stack.stack, compile_stack.size << 1, compile_stack_elt_t); if (compile_stack.stack == NULL) return REG_ESPACE; compile_stack.size <<= 1; } /* These are the values to restore when we hit end of this group. They are all relative offsets, so that if the whole pattern moves because of realloc, they will still be valid. */ COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer; COMPILE_STACK_TOP.fixup_alt_jump = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0; COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer; COMPILE_STACK_TOP.regnum = regnum; /* We will eventually replace the 0 with the number of groups inner to this one. But do not push a start_memory for groups beyond the last one we can represent in the compiled pattern. */ if (regnum <= MAX_REGNUM) { COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2; BUF_PUSH_3 (start_memory, regnum, 0); } compile_stack.avail++; fixup_alt_jump = 0; laststart = 0; begalt = b; /* If we've reached MAX_REGNUM groups, then this open won't actually generate any code, so we'll have to clear pending_exact explicitly. */ pending_exact = 0; break; case ')': if (syntax & RE_NO_BK_PARENS) goto normal_backslash; if (COMPILE_STACK_EMPTY) { if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) goto normal_backslash; else FREE_STACK_RETURN (REG_ERPAREN); } handle_close: if (fixup_alt_jump) { /* Push a dummy failure point at the end of the alternative for a possible future `pop_failure_jump' to pop. See comments at `push_dummy_failure' in `re_match_2'. */ BUF_PUSH (push_dummy_failure); /* We allocated space for this jump when we assigned to `fixup_alt_jump', in the `handle_alt' case below. */ STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1); } /* See similar code for backslashed left paren above. */ if (COMPILE_STACK_EMPTY) { if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD) goto normal_char; else FREE_STACK_RETURN (REG_ERPAREN); } /* Since we just checked for an empty stack above, this ``can't happen''. */ assert (compile_stack.avail != 0); { /* We don't just want to restore into `regnum', because later groups should continue to be numbered higher, as in `(ab)c(de)' -- the second group is #2. */ regnum_t this_group_regnum; compile_stack.avail--; begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset; fixup_alt_jump = COMPILE_STACK_TOP.fixup_alt_jump ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 : 0; laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset; this_group_regnum = COMPILE_STACK_TOP.regnum; /* If we've reached MAX_REGNUM groups, then this open won't actually generate any code, so we'll have to clear pending_exact explicitly. */ pending_exact = 0; /* We're at the end of the group, so now we know how many groups were inside this one. */ if (this_group_regnum <= MAX_REGNUM) { unsigned char *inner_group_loc = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset; *inner_group_loc = regnum - this_group_regnum; BUF_PUSH_3 (stop_memory, this_group_regnum, regnum - this_group_regnum); } } break; case '|': /* `\|'. */ if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR) goto normal_backslash; handle_alt: if (syntax & RE_LIMITED_OPS) goto normal_char; /* Insert before the previous alternative a jump which jumps to this alternative if the former fails. */ GET_BUFFER_SPACE (3); INSERT_JUMP (on_failure_jump, begalt, b + 6); pending_exact = 0; b += 3; /* The alternative before this one has a jump after it which gets executed if it gets matched. Adjust that jump so it will jump to this alternative's analogous jump (put in below, which in turn will jump to the next (if any) alternative's such jump, etc.). The last such jump jumps to the correct final destination. A picture: _____ _____ | | | | | v | v a | b | c If we are at `b', then fixup_alt_jump right now points to a three-byte space after `a'. We'll put in the jump, set fixup_alt_jump to right after `b', and leave behind three bytes which we'll fill in when we get to after `c'. */ if (fixup_alt_jump) STORE_JUMP (jump_past_alt, fixup_alt_jump, b); /* Mark and leave space for a jump after this alternative, to be filled in later either by next alternative or when know we're at the end of a series of alternatives. */ fixup_alt_jump = b; GET_BUFFER_SPACE (3); b += 3; laststart = 0; begalt = b; break; case '{': /* If \{ is a literal. */ if (!(syntax & RE_INTERVALS) /* If we're at `\{' and it's not the open-interval operator. */ || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES)) || (p - 2 == pattern && p == pend)) goto normal_backslash; handle_interval: { /* If got here, then the syntax allows intervals. */ /* At least (most) this many matches must be made. */ int lower_bound = -1, upper_bound = -1; beg_interval = p - 1; if (p == pend) { if (syntax & RE_NO_BK_BRACES) goto unfetch_interval; else FREE_STACK_RETURN (REG_EBRACE); } GET_UNSIGNED_NUMBER (lower_bound); if (c == ',') { GET_UNSIGNED_NUMBER (upper_bound); if (upper_bound < 0) upper_bound = RE_DUP_MAX; } else /* Interval such as `{1}' => match exactly once. */ upper_bound = lower_bound; if (lower_bound < 0 || upper_bound > RE_DUP_MAX || lower_bound > upper_bound) { if (syntax & RE_NO_BK_BRACES) goto unfetch_interval; else FREE_STACK_RETURN (REG_BADBR); } if (!(syntax & RE_NO_BK_BRACES)) { if (c != '\\') FREE_STACK_RETURN (REG_EBRACE); PATFETCH (c); } if (c != '}') { if (syntax & RE_NO_BK_BRACES) goto unfetch_interval; else FREE_STACK_RETURN (REG_BADBR); } /* We just parsed a valid interval. */ /* If it's invalid to have no preceding re. */ if (!laststart) { if (syntax & RE_CONTEXT_INVALID_OPS) FREE_STACK_RETURN (REG_BADRPT); else if (syntax & RE_CONTEXT_INDEP_OPS) laststart = b; else goto unfetch_interval; } /* If the upper bound is zero, don't want to succeed at all; jump from `laststart' to `b + 3', which will be the end of the buffer after we insert the jump. */ if (upper_bound == 0) { GET_BUFFER_SPACE (3); INSERT_JUMP (jump, laststart, b + 3); b += 3; } /* Otherwise, we have a nontrivial interval. When we're all done, the pattern will look like: set_number_at set_number_at succeed_n jump_n (The upper bound and `jump_n' are omitted if `upper_bound' is 1, though.) */ else { /* If the upper bound is > 1, we need to insert more at the end of the loop. */ unsigned nbytes = 10 + (upper_bound > 1) * 10; GET_BUFFER_SPACE (nbytes); /* Initialize lower bound of the `succeed_n', even though it will be set during matching by its attendant `set_number_at' (inserted next), because `re_compile_fastmap' needs to know. Jump to the `jump_n' we might insert below. */ INSERT_JUMP2 (succeed_n, laststart, b + 5 + (upper_bound > 1) * 5, lower_bound); b += 5; /* Code to initialize the lower bound. Insert before the `succeed_n'. The `5' is the last two bytes of this `set_number_at', plus 3 bytes of the following `succeed_n'. */ insert_op2 (set_number_at, laststart, 5, lower_bound, b); b += 5; if (upper_bound > 1) { /* More than one repetition is allowed, so append a backward jump to the `succeed_n' that starts this interval. When we've reached this during matching, we'll have matched the interval once, so jump back only `upper_bound - 1' times. */ STORE_JUMP2 (jump_n, b, laststart + 5, upper_bound - 1); b += 5; /* The location we want to set is the second parameter of the `jump_n'; that is `b-2' as an absolute address. `laststart' will be the `set_number_at' we're about to insert; `laststart+3' the number to set, the source for the relative address. But we are inserting into the middle of the pattern -- so everything is getting moved up by 5. Conclusion: (b - 2) - (laststart + 3) + 5, i.e., b - laststart. We insert this at the beginning of the loop so that if we fail during matching, we'll reinitialize the bounds. */ insert_op2 (set_number_at, laststart, b - laststart, upper_bound - 1, b); b += 5; } } pending_exact = 0; beg_interval = NULL; } break; unfetch_interval: /* If an invalid interval, match the characters as literals. */ assert (beg_interval); p = beg_interval; beg_interval = NULL; /* normal_char and normal_backslash need `c'. */ PATFETCH (c); if (!(syntax & RE_NO_BK_BRACES)) { if (p > pattern && p[-1] == '\\') goto normal_backslash; } goto normal_char; #ifdef emacs /* There is no way to specify the before_dot and after_dot operators. rms says this is ok. --karl */ case '=': BUF_PUSH (at_dot); break; case 's': laststart = b; PATFETCH (c); BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]); break; case 'S': laststart = b; PATFETCH (c); BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]); break; #endif /* emacs */ case 'w': laststart = b; BUF_PUSH (wordchar); break; case 'W': laststart = b; BUF_PUSH (notwordchar); break; case '<': BUF_PUSH (wordbeg); break; case '>': BUF_PUSH (wordend); break; case 'b': BUF_PUSH (wordbound); break; case 'B': BUF_PUSH (notwordbound); break; case '`': BUF_PUSH (begbuf); break; case '\'': BUF_PUSH (endbuf); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (syntax & RE_NO_BK_REFS) goto normal_char; c1 = c - '0'; if (c1 > regnum) FREE_STACK_RETURN (REG_ESUBREG); /* Can't back reference to a subexpression if inside of it. */ if (group_in_compile_stack (compile_stack, c1)) goto normal_char; laststart = b; BUF_PUSH_2 (duplicate, c1); break; case '+': case '?': if (syntax & RE_BK_PLUS_QM) goto handle_plus; else goto normal_backslash; default: normal_backslash: /* You might think it would be useful for \ to mean not to translate; but if we don't translate it it will never match anything. */ c = TRANSLATE (c); goto normal_char; } break; default: /* Expects the character in `c'. */ normal_char: /* If no exactn currently being built. */ if (!pending_exact /* If last exactn not at current position. */ || pending_exact + *pending_exact + 1 != b /* We have only one byte following the exactn for the count. */ || *pending_exact == (1 << BYTEWIDTH) - 1 /* If followed by a repetition operator. */ || *p == '*' || *p == '^' || ((syntax & RE_BK_PLUS_QM) ? *p == '\\' && (p[1] == '+' || p[1] == '?') : (*p == '+' || *p == '?')) || ((syntax & RE_INTERVALS) && ((syntax & RE_NO_BK_BRACES) ? *p == '{' : (p[0] == '\\' && p[1] == '{')))) { /* Start building a new exactn. */ laststart = b; BUF_PUSH_2 (exactn, 0); pending_exact = b - 1; } BUF_PUSH (c); (*pending_exact)++; break; } /* switch (c) */ } /* while p != pend */ /* Through the pattern now. */ if (fixup_alt_jump) STORE_JUMP (jump_past_alt, fixup_alt_jump, b); if (!COMPILE_STACK_EMPTY) FREE_STACK_RETURN (REG_EPAREN); /* If we don't want backtracking, force success the first time we reach the end of the compiled pattern. */ if (syntax & RE_NO_POSIX_BACKTRACKING) BUF_PUSH (succeed); free (compile_stack.stack); /* We have succeeded; set the length of the buffer. */ bufp->used = b - bufp->buffer; #ifdef DEBUG if (debug) { DEBUG_PRINT1 ("\nCompiled pattern: \n"); print_compiled_pattern (bufp); } #endif /* DEBUG */ #ifndef MATCH_MAY_ALLOCATE /* Initialize the failure stack to the largest possible stack. This isn't necessary unless we're trying to avoid calling alloca in the search and match routines. */ { int num_regs = bufp->re_nsub + 1; /* Since DOUBLE_FAIL_STACK refuses to double only if the current size is strictly greater than re_max_failures, the largest possible stack is 2 * re_max_failures failure points. */ if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS)) { fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS); #ifdef emacs if (! fail_stack.stack) fail_stack.stack = (fail_stack_elt_t *) xmalloc (fail_stack.size * sizeof (fail_stack_elt_t)); else fail_stack.stack = (fail_stack_elt_t *) xrealloc (fail_stack.stack, (fail_stack.size * sizeof (fail_stack_elt_t))); #else /* not emacs */ if (! fail_stack.stack) fail_stack.stack = (fail_stack_elt_t *) malloc (fail_stack.size * sizeof (fail_stack_elt_t)); else fail_stack.stack = (fail_stack_elt_t *) realloc (fail_stack.stack, (fail_stack.size * sizeof (fail_stack_elt_t))); #endif /* not emacs */ } regex_grow_registers (num_regs); } #endif /* not MATCH_MAY_ALLOCATE */ return REG_NOERROR; } /* regex_compile */ /* Subroutines for `regex_compile'. */ /* Store OP at LOC followed by two-byte integer parameter ARG. */ static void store_op1 (op, loc, arg) re_opcode_t op; unsigned char *loc; int arg; { *loc = (unsigned char) op; STORE_NUMBER (loc + 1, arg); } /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */ static void store_op2 (op, loc, arg1, arg2) re_opcode_t op; unsigned char *loc; int arg1, arg2; { *loc = (unsigned char) op; STORE_NUMBER (loc + 1, arg1); STORE_NUMBER (loc + 3, arg2); } /* Copy the bytes from LOC to END to open up three bytes of space at LOC for OP followed by two-byte integer parameter ARG. */ static void insert_op1 (op, loc, arg, end) re_opcode_t op; unsigned char *loc; int arg; unsigned char *end; { register unsigned char *pfrom = end; register unsigned char *pto = end + 3; while (pfrom != loc) *--pto = *--pfrom; store_op1 (op, loc, arg); } /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */ static void insert_op2 (op, loc, arg1, arg2, end) re_opcode_t op; unsigned char *loc; int arg1, arg2; unsigned char *end; { register unsigned char *pfrom = end; register unsigned char *pto = end + 5; while (pfrom != loc) *--pto = *--pfrom; store_op2 (op, loc, arg1, arg2); } /* P points to just after a ^ in PATTERN. Return true if that ^ comes after an alternative or a begin-subexpression. We assume there is at least one character before the ^. */ static boolean at_begline_loc_p (pattern, p, syntax) const char *pattern, *p; reg_syntax_t syntax; { const char *prev = p - 2; boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\'; return /* After a subexpression? */ (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash)) /* After an alternative? */ || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash)); } /* The dual of at_begline_loc_p. This one is for $. We assume there is at least one character after the $, i.e., `P < PEND'. */ static boolean at_endline_loc_p (p, pend, syntax) const char *p, *pend; int syntax; { const char *next = p; boolean next_backslash = *next == '\\'; const char *next_next = p + 1 < pend ? p + 1 : 0; return /* Before a subexpression? */ (syntax & RE_NO_BK_PARENS ? *next == ')' : next_backslash && next_next && *next_next == ')') /* Before an alternative? */ || (syntax & RE_NO_BK_VBAR ? *next == '|' : next_backslash && next_next && *next_next == '|'); } /* Returns true if REGNUM is in one of COMPILE_STACK's elements and false if it's not. */ static boolean group_in_compile_stack (compile_stack, regnum) compile_stack_type compile_stack; regnum_t regnum; { int this_element; for (this_element = compile_stack.avail - 1; this_element >= 0; this_element--) if (compile_stack.stack[this_element].regnum == regnum) return true; return false; } /* Read the ending character of a range (in a bracket expression) from the uncompiled pattern *P_PTR (which ends at PEND). We assume the starting character is in `P[-2]'. (`P[-1]' is the character `-'.) Then we set the translation of all bits between the starting and ending characters (inclusive) in the compiled pattern B. Return an error code. We use these short variable names so we can use the same macros as `regex_compile' itself. */ static reg_errcode_t compile_range (p_ptr, pend, translate, syntax, b) const char **p_ptr, *pend; RE_TRANSLATE_TYPE translate; reg_syntax_t syntax; unsigned char *b; { unsigned this_char; const char *p = *p_ptr; int range_start, range_end; if (p == pend) return REG_ERANGE; /* Even though the pattern is a signed `char *', we need to fetch with unsigned char *'s; if the high bit of the pattern character is set, the range endpoints will be negative if we fetch using a signed char *. We also want to fetch the endpoints without translating them; the appropriate translation is done in the bit-setting loop below. */ /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *. */ range_start = ((const unsigned char *) p)[-2]; range_end = ((const unsigned char *) p)[0]; /* Have to increment the pointer into the pattern string, so the caller isn't still at the ending character. */ (*p_ptr)++; /* If the start is after the end, the range is empty. */ if (range_start > range_end) return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR; /* Here we see why `this_char' has to be larger than an `unsigned char' -- the range is inclusive, so if `range_end' == 0xff (assuming 8-bit characters), we would otherwise go into an infinite loop, since all characters <= 0xff. */ for (this_char = range_start; this_char <= range_end; this_char++) { SET_LIST_BIT (TRANSLATE (this_char)); } return REG_NOERROR; } /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible characters can start a string that matches the pattern. This fastmap is used by re_search to skip quickly over impossible starting points. The caller must supply the address of a (1 << BYTEWIDTH)-byte data area as BUFP->fastmap. We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in the pattern buffer. Returns 0 if we succeed, -2 if an internal error. */ int re_compile_fastmap (bufp) struct re_pattern_buffer *bufp; { int j, k; #ifdef MATCH_MAY_ALLOCATE fail_stack_type fail_stack; #endif #ifndef REGEX_MALLOC char *destination; #endif /* We don't push any register information onto the failure stack. */ unsigned num_regs = 0; register char *fastmap = bufp->fastmap; unsigned char *pattern = bufp->buffer; unsigned long size = bufp->used; unsigned char *p = pattern; register unsigned char *pend = pattern + size; /* This holds the pointer to the failure stack, when it is allocated relocatably. */ #ifdef REL_ALLOC fail_stack_elt_t *failure_stack_ptr; #endif /* Assume that each path through the pattern can be null until proven otherwise. We set this false at the bottom of switch statement, to which we get only if a particular path doesn't match the empty string. */ boolean path_can_be_null = true; /* We aren't doing a `succeed_n' to begin with. */ boolean succeed_n_p = false; assert (fastmap != NULL && p != NULL); INIT_FAIL_STACK (); bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */ bufp->fastmap_accurate = 1; /* It will be when we're done. */ bufp->can_be_null = 0; while (1) { if (p == pend || *p == succeed) { /* We have reached the (effective) end of pattern. */ if (!FAIL_STACK_EMPTY ()) { bufp->can_be_null |= path_can_be_null; /* Reset for next path. */ path_can_be_null = true; p = fail_stack.stack[--fail_stack.avail].pointer; continue; } else break; } /* We should never be about to go beyond the end of the pattern. */ assert (p < pend); switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++)) { /* I guess the idea here is to simply not bother with a fastmap if a backreference is used, since it's too hard to figure out the fastmap for the corresponding group. Setting `can_be_null' stops `re_search_2' from using the fastmap, so that is all we do. */ case duplicate: bufp->can_be_null = 1; goto done; /* Following are the cases which match a character. These end with `break'. */ case exactn: fastmap[p[1]] = 1; break; case charset: for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) fastmap[j] = 1; break; case charset_not: /* Chars beyond end of map must be allowed. */ for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++) fastmap[j] = 1; for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--) if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) fastmap[j] = 1; break; case wordchar: for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) == Sword) fastmap[j] = 1; break; case notwordchar: for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) != Sword) fastmap[j] = 1; break; case anychar: { int fastmap_newline = fastmap['\n']; /* `.' matches anything ... */ for (j = 0; j < (1 << BYTEWIDTH); j++) fastmap[j] = 1; /* ... except perhaps newline. */ if (!(bufp->syntax & RE_DOT_NEWLINE)) fastmap['\n'] = fastmap_newline; /* Return if we have already set `can_be_null'; if we have, then the fastmap is irrelevant. Something's wrong here. */ else if (bufp->can_be_null) goto done; /* Otherwise, have to check alternative paths. */ break; } #ifdef emacs case syntaxspec: k = *p++; for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) == (enum syntaxcode) k) fastmap[j] = 1; break; case notsyntaxspec: k = *p++; for (j = 0; j < (1 << BYTEWIDTH); j++) if (SYNTAX (j) != (enum syntaxcode) k) fastmap[j] = 1; break; /* All cases after this match the empty string. These end with `continue'. */ case before_dot: case at_dot: case after_dot: continue; #endif /* emacs */ case no_op: case begline: case endline: case begbuf: case endbuf: case wordbound: case notwordbound: case wordbeg: case wordend: case push_dummy_failure: continue; case jump_n: case pop_failure_jump: case maybe_pop_jump: case jump: case jump_past_alt: case dummy_failure_jump: EXTRACT_NUMBER_AND_INCR (j, p); p += j; if (j > 0) continue; /* Jump backward implies we just went through the body of a loop and matched nothing. Opcode jumped to should be `on_failure_jump' or `succeed_n'. Just treat it like an ordinary jump. For a * loop, it has pushed its failure point already; if so, discard that as redundant. */ if ((re_opcode_t) *p != on_failure_jump && (re_opcode_t) *p != succeed_n) continue; p++; EXTRACT_NUMBER_AND_INCR (j, p); p += j; /* If what's on the stack is where we are now, pop it. */ if (!FAIL_STACK_EMPTY () && fail_stack.stack[fail_stack.avail - 1].pointer == p) fail_stack.avail--; continue; case on_failure_jump: case on_failure_keep_string_jump: handle_on_failure_jump: EXTRACT_NUMBER_AND_INCR (j, p); /* For some patterns, e.g., `(a?)?', `p+j' here points to the end of the pattern. We don't want to push such a point, since when we restore it above, entering the switch will increment `p' past the end of the pattern. We don't need to push such a point since we obviously won't find any more fastmap entries beyond `pend'. Such a pattern can match the null string, though. */ if (p + j < pend) { if (!PUSH_PATTERN_OP (p + j, fail_stack)) { RESET_FAIL_STACK (); return -2; } } else bufp->can_be_null = 1; if (succeed_n_p) { EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */ succeed_n_p = false; } continue; case succeed_n: /* Get to the number of times to succeed. */ p += 2; /* Increment p past the n for when k != 0. */ EXTRACT_NUMBER_AND_INCR (k, p); if (k == 0) { p -= 4; succeed_n_p = true; /* Spaghetti code alert. */ goto handle_on_failure_jump; } continue; case set_number_at: p += 4; continue; case start_memory: case stop_memory: p += 2; continue; default: abort (); /* We have listed all the cases. */ } /* switch *p++ */ /* Getting here means we have found the possible starting characters for one path of the pattern -- and that the empty string does not match. We need not follow this path further. Instead, look at the next alternative (remembered on the stack), or quit if no more. The test at the top of the loop does these things. */ path_can_be_null = false; p = pend; } /* while p */ /* Set `can_be_null' for the last path (also the first path, if the pattern is empty). */ bufp->can_be_null |= path_can_be_null; done: RESET_FAIL_STACK (); return 0; } /* re_compile_fastmap */ /* Set REGS to hold NUM_REGS registers, storing them in STARTS and ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use this memory for recording register information. STARTS and ENDS must be allocated using the malloc library routine, and must each be at least NUM_REGS * sizeof (regoff_t) bytes long. If NUM_REGS == 0, then subsequent matches should allocate their own register data. Unless this function is called, the first search or match using PATTERN_BUFFER will allocate its own register data, without freeing the old data. */ void re_set_registers (bufp, regs, num_regs, starts, ends) struct re_pattern_buffer *bufp; struct re_registers *regs; unsigned num_regs; regoff_t *starts, *ends; { if (num_regs) { bufp->regs_allocated = REGS_REALLOCATE; regs->num_regs = num_regs; regs->start = starts; regs->end = ends; } else { bufp->regs_allocated = REGS_UNALLOCATED; regs->num_regs = 0; regs->start = regs->end = (regoff_t *) 0; } } /* Searching routines. */ /* Like re_search_2, below, but only one string is specified, and doesn't let you say where to stop matching. */ int re_search (bufp, string, size, startpos, range, regs) struct re_pattern_buffer *bufp; const char *string; int size, startpos, range; struct re_registers *regs; { return re_search_2 (bufp, NULL, 0, string, size, startpos, range, regs, size); } /* Using the compiled pattern in BUFP->buffer, first tries to match the virtual concatenation of STRING1 and STRING2, starting first at index STARTPOS, then at STARTPOS + 1, and so on. STRING1 and STRING2 have length SIZE1 and SIZE2, respectively. RANGE is how far to scan while trying to match. RANGE = 0 means try only at STARTPOS; in general, the last start tried is STARTPOS + RANGE. In REGS, return the indices of the virtual concatenation of STRING1 and STRING2 that matched the entire BUFP->buffer and its contained subexpressions. Do not consider matching one past the index STOP in the virtual concatenation of STRING1 and STRING2. We return either the position in the strings at which the match was found, -1 if no match, or -2 if error (such as failure stack overflow). */ int re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop) struct re_pattern_buffer *bufp; const char *string1, *string2; int size1, size2; int startpos; int range; struct re_registers *regs; int stop; { int val; register char *fastmap = bufp->fastmap; register RE_TRANSLATE_TYPE translate = bufp->translate; int total_size = size1 + size2; int endpos = startpos + range; int anchored_start = 0; /* Check for out-of-range STARTPOS. */ if (startpos < 0 || startpos > total_size) return -1; /* Fix up RANGE if it might eventually take us outside the virtual concatenation of STRING1 and STRING2. Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */ if (endpos < 0) range = 0 - startpos; else if (endpos > total_size) range = total_size - startpos; /* If the search isn't to be a backwards one, don't waste time in a search for a pattern that must be anchored. */ if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0) { if (startpos > 0) return -1; else range = 1; } #ifdef emacs /* In a forward search for something that starts with \=. don't keep searching past point. */ if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0) { range = PT - startpos; if (range <= 0) return -1; } #endif /* emacs */ /* Update the fastmap now if not correct already. */ if (fastmap && !bufp->fastmap_accurate) if (re_compile_fastmap (bufp) == -2) return -2; /* See whether the pattern is anchored. */ if (bufp->buffer[0] == begline) anchored_start = 1; /* Loop through the string, looking for a place to start matching. */ for (;;) { /* If the pattern is anchored, skip quickly past places we cannot match. We don't bother to treat startpos == 0 specially because that case doesn't repeat. */ if (anchored_start && startpos > 0) { if (! (bufp->newline_anchor && ((startpos <= size1 ? string1[startpos - 1] : string2[startpos - size1 - 1]) == '\n'))) goto advance; } /* If a fastmap is supplied, skip quickly over characters that cannot be the start of a match. If the pattern can match the null string, however, we don't need to skip characters; we want the first null string. */ if (fastmap && startpos < total_size && !bufp->can_be_null) { if (range > 0) /* Searching forwards. */ { register const char *d; register int lim = 0; int irange = range; if (startpos < size1 && startpos + range >= size1) lim = range - (size1 - startpos); d = (startpos >= size1 ? string2 - size1 : string1) + startpos; /* Written out as an if-else to avoid testing `translate' inside the loop. */ if (translate) while (range > lim && !fastmap[(unsigned char) translate[(unsigned char) *d++]]) range--; else while (range > lim && !fastmap[(unsigned char) *d++]) range--; startpos += irange - range; } else /* Searching backwards. */ { register char c = (size1 == 0 || startpos >= size1 ? string2[startpos - size1] : string1[startpos]); if (!fastmap[(unsigned char) TRANSLATE (c)]) goto advance; } } /* If can't match the null string, and that's all we have left, fail. */ if (range >= 0 && startpos == total_size && fastmap && !bufp->can_be_null) return -1; val = re_match_2_internal (bufp, string1, size1, string2, size2, startpos, regs, stop); #ifndef REGEX_MALLOC #ifdef C_ALLOCA alloca (0); #endif #endif if (val >= 0) return startpos; if (val == -2) return -2; advance: if (!range) break; else if (range > 0) { range--; startpos++; } else { range++; startpos--; } } return -1; } /* re_search_2 */ /* Declarations and macros for re_match_2. */ static int bcmp_translate (); static boolean alt_match_null_string_p (), common_op_match_null_string_p (), group_match_null_string_p (); /* This converts PTR, a pointer into one of the search strings `string1' and `string2' into an offset from the beginning of that string. */ #define POINTER_TO_OFFSET(ptr) \ (FIRST_STRING_P (ptr) \ ? ((regoff_t) ((ptr) - string1)) \ : ((regoff_t) ((ptr) - string2 + size1))) /* Macros for dealing with the split strings in re_match_2. */ #define MATCHING_IN_FIRST_STRING (dend == end_match_1) /* Call before fetching a character with *d. This switches over to string2 if necessary. */ #define PREFETCH() \ while (d == dend) \ { \ /* End of string2 => fail. */ \ if (dend == end_match_2) \ goto fail; \ /* End of string1 => advance to string2. */ \ d = string2; \ dend = end_match_2; \ } /* Test if at very beginning or at very end of the virtual concatenation of `string1' and `string2'. If only one string, it's `string2'. */ #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2) #define AT_STRINGS_END(d) ((d) == end2) /* Test if D points to a character which is word-constituent. We have two special cases to check for: if past the end of string1, look at the first character in string2; and if before the beginning of string2, look at the last character in string1. */ #define WORDCHAR_P(d) \ (SYNTAX ((d) == end1 ? *string2 \ : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \ == Sword) /* Disabled due to a compiler bug -- see comment at case wordbound */ #if 0 /* Test if the character before D and the one at D differ with respect to being word-constituent. */ #define AT_WORD_BOUNDARY(d) \ (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \ || WORDCHAR_P (d - 1) != WORDCHAR_P (d)) #endif /* Free everything we malloc. */ #ifdef MATCH_MAY_ALLOCATE #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else #define FREE_VARIABLES() \ do { \ REGEX_FREE_STACK (fail_stack.stack); \ FREE_VAR (regstart); \ FREE_VAR (regend); \ FREE_VAR (old_regstart); \ FREE_VAR (old_regend); \ FREE_VAR (best_regstart); \ FREE_VAR (best_regend); \ FREE_VAR (reg_info); \ FREE_VAR (reg_dummy); \ FREE_VAR (reg_info_dummy); \ } while (0) #else #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */ #endif /* not MATCH_MAY_ALLOCATE */ /* These values must meet several constraints. They must not be valid register values; since we have a limit of 255 registers (because we use only one byte in the pattern for the register number), we can use numbers larger than 255. They must differ by 1, because of NUM_FAILURE_ITEMS above. And the value for the lowest register must be larger than the value for the highest register, so we do not try to actually save any registers when none are active. */ #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH) #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1) /* Matching routines. */ #ifndef emacs /* Emacs never uses this. */ /* re_match is like re_match_2 except it takes only a single string. */ int re_match (bufp, string, size, pos, regs) struct re_pattern_buffer *bufp; const char *string; int size, pos; struct re_registers *regs; { int result = re_match_2_internal (bufp, NULL, 0, string, size, pos, regs, size); alloca (0); return result; } #endif /* not emacs */ /* re_match_2 matches the compiled pattern in BUFP against the the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1 and SIZE2, respectively). We start matching at POS, and stop matching at STOP. If REGS is non-null and the `no_sub' field of BUFP is nonzero, we store offsets for the substring each group matched in REGS. See the documentation for exactly how many groups we fill. We return -1 if no match, -2 if an internal error (such as the failure stack overflowing). Otherwise, we return the length of the matched substring. */ int re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop) struct re_pattern_buffer *bufp; const char *string1, *string2; int size1, size2; int pos; struct re_registers *regs; int stop; { int result = re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop); alloca (0); return result; } /* This is a separate function so that we can force an alloca cleanup afterwards. */ static int re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop) struct re_pattern_buffer *bufp; const char *string1, *string2; int size1, size2; int pos; struct re_registers *regs; int stop; { /* General temporaries. */ int mcnt; unsigned char *p1; /* Just past the end of the corresponding string. */ const char *end1, *end2; /* Pointers into string1 and string2, just past the last characters in each to consider matching. */ const char *end_match_1, *end_match_2; /* Where we are in the data, and the end of the current string. */ const char *d, *dend; /* Where we are in the pattern, and the end of the pattern. */ unsigned char *p = bufp->buffer; register unsigned char *pend = p + bufp->used; /* Mark the opcode just after a start_memory, so we can test for an empty subpattern when we get to the stop_memory. */ unsigned char *just_past_start_mem = 0; /* We use this to map every character in the string. */ RE_TRANSLATE_TYPE translate = bufp->translate; /* Failure point stack. Each place that can handle a failure further down the line pushes a failure point on this stack. It consists of restart, regend, and reg_info for all registers corresponding to the subexpressions we're currently inside, plus the number of such registers, and, finally, two char *'s. The first char * is where to resume scanning the pattern; the second one is where to resume scanning the strings. If the latter is zero, the failure point is a ``dummy''; if a failure happens and the failure point is a dummy, it gets discarded and the next next one is tried. */ #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */ fail_stack_type fail_stack; #endif #ifdef DEBUG static unsigned failure_id = 0; unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0; #endif /* This holds the pointer to the failure stack, when it is allocated relocatably. */ #ifdef REL_ALLOC fail_stack_elt_t *failure_stack_ptr; #endif /* We fill all the registers internally, independent of what we return, for use in backreferences. The number here includes an element for register zero. */ unsigned num_regs = bufp->re_nsub + 1; /* The currently active registers. */ unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG; unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG; /* Information on the contents of registers. These are pointers into the input strings; they record just what was matched (on this attempt) by a subexpression part of the pattern, that is, the regnum-th regstart pointer points to where in the pattern we began matching and the regnum-th regend points to right after where we stopped matching the regnum-th subexpression. (The zeroth register keeps track of what the whole pattern matches.) */ #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ const char **regstart, **regend; #endif /* If a group that's operated upon by a repetition operator fails to match anything, then the register for its start will need to be restored because it will have been set to wherever in the string we are when we last see its open-group operator. Similarly for a register's end. */ #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ const char **old_regstart, **old_regend; #endif /* The is_active field of reg_info helps us keep track of which (possibly nested) subexpressions we are currently in. The matched_something field of reg_info[reg_num] helps us tell whether or not we have matched any of the pattern so far this time through the reg_num-th subexpression. These two fields get reset each time through any loop their register is in. */ #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */ register_info_type *reg_info; #endif /* The following record the register info as found in the above variables when we find a match better than any we've seen before. This happens as we backtrack through the failure points, which in turn happens only if we have not yet matched the entire string. */ unsigned best_regs_set = false; #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ const char **best_regstart, **best_regend; #endif /* Logically, this is `best_regend[0]'. But we don't want to have to allocate space for that if we're not allocating space for anything else (see below). Also, we never need info about register 0 for any of the other register vectors, and it seems rather a kludge to treat `best_regend' differently than the rest. So we keep track of the end of the best match so far in a separate variable. We initialize this to NULL so that when we backtrack the first time and need to test it, it's not garbage. */ const char *match_end = NULL; /* This helps SET_REGS_MATCHED avoid doing redundant work. */ int set_regs_matched_done = 0; /* Used when we pop values we don't care about. */ #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */ const char **reg_dummy; register_info_type *reg_info_dummy; #endif #ifdef DEBUG /* Counts the total number of registers pushed. */ unsigned num_regs_pushed = 0; #endif DEBUG_PRINT1 ("\n\nEntering re_match_2.\n"); INIT_FAIL_STACK (); #ifdef MATCH_MAY_ALLOCATE /* Do not bother to initialize all the register variables if there are no groups in the pattern, as it takes a fair amount of time. If there are groups, we include space for register 0 (the whole pattern), even though we never use it, since it simplifies the array indexing. We should fix this. */ if (bufp->re_nsub) { regstart = REGEX_TALLOC (num_regs, const char *); regend = REGEX_TALLOC (num_regs, const char *); old_regstart = REGEX_TALLOC (num_regs, const char *); old_regend = REGEX_TALLOC (num_regs, const char *); best_regstart = REGEX_TALLOC (num_regs, const char *); best_regend = REGEX_TALLOC (num_regs, const char *); reg_info = REGEX_TALLOC (num_regs, register_info_type); reg_dummy = REGEX_TALLOC (num_regs, const char *); reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type); if (!(regstart && regend && old_regstart && old_regend && reg_info && best_regstart && best_regend && reg_dummy && reg_info_dummy)) { FREE_VARIABLES (); return -2; } } else { /* We must initialize all our variables to NULL, so that `FREE_VARIABLES' doesn't try to free them. */ regstart = regend = old_regstart = old_regend = best_regstart = best_regend = reg_dummy = NULL; reg_info = reg_info_dummy = (register_info_type *) NULL; } #endif /* MATCH_MAY_ALLOCATE */ /* The starting position is bogus. */ if (pos < 0 || pos > size1 + size2) { FREE_VARIABLES (); return -1; } /* Initialize subexpression text positions to -1 to mark ones that no start_memory/stop_memory has been seen for. Also initialize the register information struct. */ for (mcnt = 1; mcnt < num_regs; mcnt++) { regstart[mcnt] = regend[mcnt] = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE; REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE; IS_ACTIVE (reg_info[mcnt]) = 0; MATCHED_SOMETHING (reg_info[mcnt]) = 0; EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0; } /* We move `string1' into `string2' if the latter's empty -- but not if `string1' is null. */ if (size2 == 0 && string1 != NULL) { string2 = string1; size2 = size1; string1 = 0; size1 = 0; } end1 = string1 + size1; end2 = string2 + size2; /* Compute where to stop matching, within the two strings. */ if (stop <= size1) { end_match_1 = string1 + stop; end_match_2 = string2; } else { end_match_1 = end1; end_match_2 = string2 + stop - size1; } /* `p' scans through the pattern as `d' scans through the data. `dend' is the end of the input string that `d' points within. `d' is advanced into the following input string whenever necessary, but this happens before fetching; therefore, at the beginning of the loop, `d' can be pointing at the end of a string, but it cannot equal `string2'. */ if (size1 > 0 && pos <= size1) { d = string1 + pos; dend = end_match_1; } else { d = string2 + pos - size1; dend = end_match_2; } DEBUG_PRINT1 ("The compiled pattern is: "); DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend); DEBUG_PRINT1 ("The string to match is: `"); DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2); DEBUG_PRINT1 ("'\n"); /* This loops over pattern commands. It exits by returning from the function if the match is complete, or it drops through if the match fails at this starting point in the input data. */ for (;;) { DEBUG_PRINT2 ("\n0x%x: ", p); if (p == pend) { /* End of pattern means we might have succeeded. */ DEBUG_PRINT1 ("end of pattern ... "); /* If we haven't matched the entire string, and we want the longest match, try backtracking. */ if (d != end_match_2) { /* 1 if this match ends in the same string (string1 or string2) as the best previous match. */ boolean same_str_p = (FIRST_STRING_P (match_end) == MATCHING_IN_FIRST_STRING); /* 1 if this match is the best seen so far. */ boolean best_match_p; /* AIX compiler got confused when this was combined with the previous declaration. */ if (same_str_p) best_match_p = d > match_end; else best_match_p = !MATCHING_IN_FIRST_STRING; DEBUG_PRINT1 ("backtracking.\n"); if (!FAIL_STACK_EMPTY ()) { /* More failure points to try. */ /* If exceeds best match so far, save it. */ if (!best_regs_set || best_match_p) { best_regs_set = true; match_end = d; DEBUG_PRINT1 ("\nSAVING match as best so far.\n"); for (mcnt = 1; mcnt < num_regs; mcnt++) { best_regstart[mcnt] = regstart[mcnt]; best_regend[mcnt] = regend[mcnt]; } } goto fail; } /* If no failure points, don't restore garbage. And if last match is real best match, don't restore second best one. */ else if (best_regs_set && !best_match_p) { restore_best_regs: /* Restore best match. It may happen that `dend == end_match_1' while the restored d is in string2. For example, the pattern `x.*y.*z' against the strings `x-' and `y-z-', if the two strings are not consecutive in memory. */ DEBUG_PRINT1 ("Restoring best registers.\n"); d = match_end; dend = ((d >= string1 && d <= end1) ? end_match_1 : end_match_2); for (mcnt = 1; mcnt < num_regs; mcnt++) { regstart[mcnt] = best_regstart[mcnt]; regend[mcnt] = best_regend[mcnt]; } } } /* d != end_match_2 */ succeed_label: DEBUG_PRINT1 ("Accepting match.\n"); /* If caller wants register contents data back, do it. */ if (regs && !bufp->no_sub) { /* Have the register data arrays been allocated? */ if (bufp->regs_allocated == REGS_UNALLOCATED) { /* No. So allocate them with malloc. We need one extra element beyond `num_regs' for the `-1' marker GNU code uses. */ regs->num_regs = MAX (RE_NREGS, num_regs + 1); regs->start = TALLOC (regs->num_regs, regoff_t); regs->end = TALLOC (regs->num_regs, regoff_t); if (regs->start == NULL || regs->end == NULL) { FREE_VARIABLES (); return -2; } bufp->regs_allocated = REGS_REALLOCATE; } else if (bufp->regs_allocated == REGS_REALLOCATE) { /* Yes. If we need more elements than were already allocated, reallocate them. If we need fewer, just leave it alone. */ if (regs->num_regs < num_regs + 1) { regs->num_regs = num_regs + 1; RETALLOC (regs->start, regs->num_regs, regoff_t); RETALLOC (regs->end, regs->num_regs, regoff_t); if (regs->start == NULL || regs->end == NULL) { FREE_VARIABLES (); return -2; } } } else { /* These braces fend off a "empty body in an else-statement" warning under GCC when assert expands to nothing. */ assert (bufp->regs_allocated == REGS_FIXED); } /* Convert the pointer data in `regstart' and `regend' to indices. Register zero has to be set differently, since we haven't kept track of any info for it. */ if (regs->num_regs > 0) { regs->start[0] = pos; regs->end[0] = (MATCHING_IN_FIRST_STRING ? ((regoff_t) (d - string1)) : ((regoff_t) (d - string2 + size1))); } /* Go through the first `min (num_regs, regs->num_regs)' registers, since that is all we initialized. */ for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++) { if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt])) regs->start[mcnt] = regs->end[mcnt] = -1; else { regs->start[mcnt] = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]); regs->end[mcnt] = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]); } } /* If the regs structure we return has more elements than were in the pattern, set the extra elements to -1. If we (re)allocated the registers, this is the case, because we always allocate enough to have at least one -1 at the end. */ for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++) regs->start[mcnt] = regs->end[mcnt] = -1; } /* regs && !bufp->no_sub */ DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n", nfailure_points_pushed, nfailure_points_popped, nfailure_points_pushed - nfailure_points_popped); DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed); mcnt = d - pos - (MATCHING_IN_FIRST_STRING ? string1 : string2 - size1); DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt); FREE_VARIABLES (); return mcnt; } /* Otherwise match next pattern command. */ switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++)) { /* Ignore these. Used to ignore the n of succeed_n's which currently have n == 0. */ case no_op: DEBUG_PRINT1 ("EXECUTING no_op.\n"); break; case succeed: DEBUG_PRINT1 ("EXECUTING succeed.\n"); goto succeed_label; /* Match the next n pattern characters exactly. The following byte in the pattern defines n, and the n bytes after that are the characters to match. */ case exactn: mcnt = *p++; DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt); /* This is written out as an if-else so we don't waste time testing `translate' inside the loop. */ if (translate) { do { PREFETCH (); if ((unsigned char) translate[(unsigned char) *d++] != (unsigned char) *p++) goto fail; } while (--mcnt); } else { do { PREFETCH (); if (*d++ != (char) *p++) goto fail; } while (--mcnt); } SET_REGS_MATCHED (); break; /* Match any character except possibly a newline or a null. */ case anychar: DEBUG_PRINT1 ("EXECUTING anychar.\n"); PREFETCH (); if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n') || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000')) goto fail; SET_REGS_MATCHED (); DEBUG_PRINT2 (" Matched `%d'.\n", *d); d++; break; case charset: case charset_not: { register unsigned char c; boolean not = (re_opcode_t) *(p - 1) == charset_not; DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : ""); PREFETCH (); c = TRANSLATE (*d); /* The character to match. */ /* Cast to `unsigned' instead of `unsigned char' in case the bit list is a full 32 bytes long. */ if (c < (unsigned) (*p * BYTEWIDTH) && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) not = !not; p += 1 + *p; if (!not) goto fail; SET_REGS_MATCHED (); d++; break; } /* The beginning of a group is represented by start_memory. The arguments are the register number in the next byte, and the number of groups inner to this one in the next. The text matched within the group is recorded (in the internal registers data structure) under the register number. */ case start_memory: DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]); /* Find out if this group can match the empty string. */ p1 = p; /* To send to group_match_null_string_p. */ if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE) REG_MATCH_NULL_STRING_P (reg_info[*p]) = group_match_null_string_p (&p1, pend, reg_info); /* Save the position in the string where we were the last time we were at this open-group operator in case the group is operated upon by a repetition operator, e.g., with `(a*)*b' against `ab'; then we want to ignore where we are now in the string in case this attempt to match fails. */ old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p]) ? REG_UNSET (regstart[*p]) ? d : regstart[*p] : regstart[*p]; DEBUG_PRINT2 (" old_regstart: %d\n", POINTER_TO_OFFSET (old_regstart[*p])); regstart[*p] = d; DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p])); IS_ACTIVE (reg_info[*p]) = 1; MATCHED_SOMETHING (reg_info[*p]) = 0; /* Clear this whenever we change the register activity status. */ set_regs_matched_done = 0; /* This is the new highest active register. */ highest_active_reg = *p; /* If nothing was active before, this is the new lowest active register. */ if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) lowest_active_reg = *p; /* Move past the register number and inner group count. */ p += 2; just_past_start_mem = p; break; /* The stop_memory opcode represents the end of a group. Its arguments are the same as start_memory's: the register number, and the number of inner groups. */ case stop_memory: DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]); /* We need to save the string position the last time we were at this close-group operator in case the group is operated upon by a repetition operator, e.g., with `((a*)*(b*)*)*' against `aba'; then we want to ignore where we are now in the string in case this attempt to match fails. */ old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p]) ? REG_UNSET (regend[*p]) ? d : regend[*p] : regend[*p]; DEBUG_PRINT2 (" old_regend: %d\n", POINTER_TO_OFFSET (old_regend[*p])); regend[*p] = d; DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p])); /* This register isn't active anymore. */ IS_ACTIVE (reg_info[*p]) = 0; /* Clear this whenever we change the register activity status. */ set_regs_matched_done = 0; /* If this was the only register active, nothing is active anymore. */ if (lowest_active_reg == highest_active_reg) { lowest_active_reg = NO_LOWEST_ACTIVE_REG; highest_active_reg = NO_HIGHEST_ACTIVE_REG; } else { /* We must scan for the new highest active register, since it isn't necessarily one less than now: consider (a(b)c(d(e)f)g). When group 3 ends, after the f), the new highest active register is 1. */ unsigned char r = *p - 1; while (r > 0 && !IS_ACTIVE (reg_info[r])) r--; /* If we end up at register zero, that means that we saved the registers as the result of an `on_failure_jump', not a `start_memory', and we jumped to past the innermost `stop_memory'. For example, in ((.)*) we save registers 1 and 2 as a result of the *, but when we pop back to the second ), we are at the stop_memory 1. Thus, nothing is active. */ if (r == 0) { lowest_active_reg = NO_LOWEST_ACTIVE_REG; highest_active_reg = NO_HIGHEST_ACTIVE_REG; } else highest_active_reg = r; } /* If just failed to match something this time around with a group that's operated on by a repetition operator, try to force exit from the ``loop'', and restore the register information for this group that we had before trying this last match. */ if ((!MATCHED_SOMETHING (reg_info[*p]) || just_past_start_mem == p - 1) && (p + 2) < pend) { boolean is_a_jump_n = false; p1 = p + 2; mcnt = 0; switch ((re_opcode_t) *p1++) { case jump_n: is_a_jump_n = true; case pop_failure_jump: case maybe_pop_jump: case jump: case dummy_failure_jump: EXTRACT_NUMBER_AND_INCR (mcnt, p1); if (is_a_jump_n) p1 += 2; break; default: /* do nothing */ ; } p1 += mcnt; /* If the next operation is a jump backwards in the pattern to an on_failure_jump right before the start_memory corresponding to this stop_memory, exit from the loop by forcing a failure after pushing on the stack the on_failure_jump's jump in the pattern, and d. */ if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) { /* If this group ever matched anything, then restore what its registers were before trying this last failed match, e.g., with `(a*)*b' against `ab' for regstart[1], and, e.g., with `((a*)*(b*)*)*' against `aba' for regend[3]. Also restore the registers for inner groups for, e.g., `((a*)(b*))*' against `aba' (register 3 would otherwise get trashed). */ if (EVER_MATCHED_SOMETHING (reg_info[*p])) { unsigned r; EVER_MATCHED_SOMETHING (reg_info[*p]) = 0; /* Restore this and inner groups' (if any) registers. */ for (r = *p; r < *p + *(p + 1); r++) { regstart[r] = old_regstart[r]; /* xx why this test? */ if (old_regend[r] >= regstart[r]) regend[r] = old_regend[r]; } } p1++; EXTRACT_NUMBER_AND_INCR (mcnt, p1); PUSH_FAILURE_POINT (p1 + mcnt, d, -2); goto fail; } } /* Move past the register number and the inner group count. */ p += 2; break; /* \ has been turned into a `duplicate' command which is followed by the numeric value of as the register number. */ case duplicate: { register const char *d2, *dend2; int regno = *p++; /* Get which register to match against. */ DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno); /* Can't back reference a group which we've never matched. */ if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno])) goto fail; /* Where in input to try to start matching. */ d2 = regstart[regno]; /* Where to stop matching; if both the place to start and the place to stop matching are in the same string, then set to the place to stop, otherwise, for now have to use the end of the first string. */ dend2 = ((FIRST_STRING_P (regstart[regno]) == FIRST_STRING_P (regend[regno])) ? regend[regno] : end_match_1); for (;;) { /* If necessary, advance to next segment in register contents. */ while (d2 == dend2) { if (dend2 == end_match_2) break; if (dend2 == regend[regno]) break; /* End of string1 => advance to string2. */ d2 = string2; dend2 = regend[regno]; } /* At end of register contents => success */ if (d2 == dend2) break; /* If necessary, advance to next segment in data. */ PREFETCH (); /* How many characters left in this segment to match. */ mcnt = dend - d; /* Want how many consecutive characters we can match in one shot, so, if necessary, adjust the count. */ if (mcnt > dend2 - d2) mcnt = dend2 - d2; /* Compare that many; failure if mismatch, else move past them. */ if (translate ? bcmp_translate (d, d2, mcnt, translate) : bcmp (d, d2, mcnt)) goto fail; d += mcnt, d2 += mcnt; /* Do this because we've match some characters. */ SET_REGS_MATCHED (); } } break; /* begline matches the empty string at the beginning of the string (unless `not_bol' is set in `bufp'), and, if `newline_anchor' is set, after newlines. */ case begline: DEBUG_PRINT1 ("EXECUTING begline.\n"); if (AT_STRINGS_BEG (d)) { if (!bufp->not_bol) break; } else if (d[-1] == '\n' && bufp->newline_anchor) { break; } /* In all other cases, we fail. */ goto fail; /* endline is the dual of begline. */ case endline: DEBUG_PRINT1 ("EXECUTING endline.\n"); if (AT_STRINGS_END (d)) { if (!bufp->not_eol) break; } /* We have to ``prefetch'' the next character. */ else if ((d == end1 ? *string2 : *d) == '\n' && bufp->newline_anchor) { break; } goto fail; /* Match at the very beginning of the data. */ case begbuf: DEBUG_PRINT1 ("EXECUTING begbuf.\n"); if (AT_STRINGS_BEG (d)) break; goto fail; /* Match at the very end of the data. */ case endbuf: DEBUG_PRINT1 ("EXECUTING endbuf.\n"); if (AT_STRINGS_END (d)) break; goto fail; /* on_failure_keep_string_jump is used to optimize `.*\n'. It pushes NULL as the value for the string on the stack. Then `pop_failure_point' will keep the current value for the string, instead of restoring it. To see why, consider matching `foo\nbar' against `.*\n'. The .* matches the foo; then the . fails against the \n. But the next thing we want to do is match the \n against the \n; if we restored the string value, we would be back at the foo. Because this is used only in specific cases, we don't need to check all the things that `on_failure_jump' does, to make sure the right things get saved on the stack. Hence we don't share its code. The only reason to push anything on the stack at all is that otherwise we would have to change `anychar's code to do something besides goto fail in this case; that seems worse than this. */ case on_failure_keep_string_jump: DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump"); EXTRACT_NUMBER_AND_INCR (mcnt, p); DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt); PUSH_FAILURE_POINT (p + mcnt, NULL, -2); break; /* Uses of on_failure_jump: Each alternative starts with an on_failure_jump that points to the beginning of the next alternative. Each alternative except the last ends with a jump that in effect jumps past the rest of the alternatives. (They really jump to the ending jump of the following alternative, because tensioning these jumps is a hassle.) Repeats start with an on_failure_jump that points past both the repetition text and either the following jump or pop_failure_jump back to this on_failure_jump. */ case on_failure_jump: on_failure: DEBUG_PRINT1 ("EXECUTING on_failure_jump"); EXTRACT_NUMBER_AND_INCR (mcnt, p); DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt); /* If this on_failure_jump comes right before a group (i.e., the original * applied to a group), save the information for that group and all inner ones, so that if we fail back to this point, the group's information will be correct. For example, in \(a*\)*\1, we need the preceding group, and in \(zz\(a*\)b*\)\2, we need the inner group. */ /* We can't use `p' to check ahead because we push a failure point to `p + mcnt' after we do this. */ p1 = p; /* We need to skip no_op's before we look for the start_memory in case this on_failure_jump is happening as the result of a completed succeed_n, as in \(a\)\{1,3\}b\1 against aba. */ while (p1 < pend && (re_opcode_t) *p1 == no_op) p1++; if (p1 < pend && (re_opcode_t) *p1 == start_memory) { /* We have a new highest active register now. This will get reset at the start_memory we are about to get to, but we will have saved all the registers relevant to this repetition op, as described above. */ highest_active_reg = *(p1 + 1) + *(p1 + 2); if (lowest_active_reg == NO_LOWEST_ACTIVE_REG) lowest_active_reg = *(p1 + 1); } DEBUG_PRINT1 (":\n"); PUSH_FAILURE_POINT (p + mcnt, d, -2); break; /* A smart repeat ends with `maybe_pop_jump'. We change it to either `pop_failure_jump' or `jump'. */ case maybe_pop_jump: EXTRACT_NUMBER_AND_INCR (mcnt, p); DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt); { register unsigned char *p2 = p; /* Compare the beginning of the repeat with what in the pattern follows its end. If we can establish that there is nothing that they would both match, i.e., that we would have to backtrack because of (as in, e.g., `a*a') then we can change to pop_failure_jump, because we'll never have to backtrack. This is not true in the case of alternatives: in `(a|ab)*' we do need to backtrack to the `ab' alternative (e.g., if the string was `ab'). But instead of trying to detect that here, the alternative has put on a dummy failure point which is what we will end up popping. */ /* Skip over open/close-group commands. If what follows this loop is a ...+ construct, look at what begins its body, since we will have to match at least one of that. */ while (1) { if (p2 + 2 < pend && ((re_opcode_t) *p2 == stop_memory || (re_opcode_t) *p2 == start_memory)) p2 += 3; else if (p2 + 6 < pend && (re_opcode_t) *p2 == dummy_failure_jump) p2 += 6; else break; } p1 = p + mcnt; /* p1[0] ... p1[2] are the `on_failure_jump' corresponding to the `maybe_finalize_jump' of this case. Examine what follows. */ /* If we're at the end of the pattern, we can change. */ if (p2 == pend) { /* Consider what happens when matching ":\(.*\)" against ":/". I don't really understand this code yet. */ p[-3] = (unsigned char) pop_failure_jump; DEBUG_PRINT1 (" End of pattern: change to `pop_failure_jump'.\n"); } else if ((re_opcode_t) *p2 == exactn || (bufp->newline_anchor && (re_opcode_t) *p2 == endline)) { register unsigned char c = *p2 == (unsigned char) endline ? '\n' : p2[2]; if ((re_opcode_t) p1[3] == exactn && p1[5] != c) { p[-3] = (unsigned char) pop_failure_jump; DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n", c, p1[5]); } else if ((re_opcode_t) p1[3] == charset || (re_opcode_t) p1[3] == charset_not) { int not = (re_opcode_t) p1[3] == charset_not; if (c < (unsigned char) (p1[4] * BYTEWIDTH) && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH))) not = !not; /* `not' is equal to 1 if c would match, which means that we can't change to pop_failure_jump. */ if (!not) { p[-3] = (unsigned char) pop_failure_jump; DEBUG_PRINT1 (" No match => pop_failure_jump.\n"); } } } else if ((re_opcode_t) *p2 == charset) { #ifdef DEBUG register unsigned char c = *p2 == (unsigned char) endline ? '\n' : p2[2]; #endif if ((re_opcode_t) p1[3] == exactn && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5] && (p2[2 + p1[5] / BYTEWIDTH] & (1 << (p1[5] % BYTEWIDTH))))) { p[-3] = (unsigned char) pop_failure_jump; DEBUG_PRINT3 (" %c != %c => pop_failure_jump.\n", c, p1[5]); } else if ((re_opcode_t) p1[3] == charset_not) { int idx; /* We win if the charset_not inside the loop lists every character listed in the charset after. */ for (idx = 0; idx < (int) p2[1]; idx++) if (! (p2[2 + idx] == 0 || (idx < (int) p1[4] && ((p2[2 + idx] & ~ p1[5 + idx]) == 0)))) break; if (idx == p2[1]) { p[-3] = (unsigned char) pop_failure_jump; DEBUG_PRINT1 (" No match => pop_failure_jump.\n"); } } else if ((re_opcode_t) p1[3] == charset) { int idx; /* We win if the charset inside the loop has no overlap with the one after the loop. */ for (idx = 0; idx < (int) p2[1] && idx < (int) p1[4]; idx++) if ((p2[2 + idx] & p1[5 + idx]) != 0) break; if (idx == p2[1] || idx == p1[4]) { p[-3] = (unsigned char) pop_failure_jump; DEBUG_PRINT1 (" No match => pop_failure_jump.\n"); } } } } p -= 2; /* Point at relative address again. */ if ((re_opcode_t) p[-1] != pop_failure_jump) { p[-1] = (unsigned char) jump; DEBUG_PRINT1 (" Match => jump.\n"); goto unconditional_jump; } /* Note fall through. */ /* The end of a simple repeat has a pop_failure_jump back to its matching on_failure_jump, where the latter will push a failure point. The pop_failure_jump takes off failure points put on by this pop_failure_jump's matching on_failure_jump; we got through the pattern to here from the matching on_failure_jump, so didn't fail. */ case pop_failure_jump: { /* We need to pass separate storage for the lowest and highest registers, even though we don't care about the actual values. Otherwise, we will restore only one register from the stack, since lowest will == highest in `pop_failure_point'. */ unsigned dummy_low_reg, dummy_high_reg; unsigned char *pdummy; const char *sdummy; DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n"); POP_FAILURE_POINT (sdummy, pdummy, dummy_low_reg, dummy_high_reg, reg_dummy, reg_dummy, reg_info_dummy); } /* Note fall through. */ /* Unconditionally jump (without popping any failure points). */ case jump: unconditional_jump: EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */ DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt); p += mcnt; /* Do the jump. */ DEBUG_PRINT2 ("(to 0x%x).\n", p); break; /* We need this opcode so we can detect where alternatives end in `group_match_null_string_p' et al. */ case jump_past_alt: DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n"); goto unconditional_jump; /* Normally, the on_failure_jump pushes a failure point, which then gets popped at pop_failure_jump. We will end up at pop_failure_jump, also, and with a pattern of, say, `a+', we are skipping over the on_failure_jump, so we have to push something meaningless for pop_failure_jump to pop. */ case dummy_failure_jump: DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n"); /* It doesn't matter what we push for the string here. What the code at `fail' tests is the value for the pattern. */ PUSH_FAILURE_POINT (0, 0, -2); goto unconditional_jump; /* At the end of an alternative, we need to push a dummy failure point in case we are followed by a `pop_failure_jump', because we don't want the failure point for the alternative to be popped. For example, matching `(a|ab)*' against `aab' requires that we match the `ab' alternative. */ case push_dummy_failure: DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n"); /* See comments just above at `dummy_failure_jump' about the two zeroes. */ PUSH_FAILURE_POINT (0, 0, -2); break; /* Have to succeed matching what follows at least n times. After that, handle like `on_failure_jump'. */ case succeed_n: EXTRACT_NUMBER (mcnt, p + 2); DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt); assert (mcnt >= 0); /* Originally, this is how many times we HAVE to succeed. */ if (mcnt > 0) { mcnt--; p += 2; STORE_NUMBER_AND_INCR (p, mcnt); DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p, mcnt); } else if (mcnt == 0) { DEBUG_PRINT2 (" Setting two bytes from 0x%x to no_op.\n", p+2); p[2] = (unsigned char) no_op; p[3] = (unsigned char) no_op; goto on_failure; } break; case jump_n: EXTRACT_NUMBER (mcnt, p + 2); DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt); /* Originally, this is how many times we CAN jump. */ if (mcnt) { mcnt--; STORE_NUMBER (p + 2, mcnt); goto unconditional_jump; } /* If don't have to jump any more, skip over the rest of command. */ else p += 4; break; case set_number_at: { DEBUG_PRINT1 ("EXECUTING set_number_at.\n"); EXTRACT_NUMBER_AND_INCR (mcnt, p); p1 = p + mcnt; EXTRACT_NUMBER_AND_INCR (mcnt, p); DEBUG_PRINT3 (" Setting 0x%x to %d.\n", p1, mcnt); STORE_NUMBER (p1, mcnt); break; } #if 0 /* The DEC Alpha C compiler 3.x generates incorrect code for the test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of AT_WORD_BOUNDARY, so this code is disabled. Expanding the macro and introducing temporary variables works around the bug. */ case wordbound: DEBUG_PRINT1 ("EXECUTING wordbound.\n"); if (AT_WORD_BOUNDARY (d)) break; goto fail; case notwordbound: DEBUG_PRINT1 ("EXECUTING notwordbound.\n"); if (AT_WORD_BOUNDARY (d)) goto fail; break; #else case wordbound: { boolean prevchar, thischar; DEBUG_PRINT1 ("EXECUTING wordbound.\n"); if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)) break; prevchar = WORDCHAR_P (d - 1); thischar = WORDCHAR_P (d); if (prevchar != thischar) break; goto fail; } case notwordbound: { boolean prevchar, thischar; DEBUG_PRINT1 ("EXECUTING notwordbound.\n"); if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)) goto fail; prevchar = WORDCHAR_P (d - 1); thischar = WORDCHAR_P (d); if (prevchar != thischar) goto fail; break; } #endif case wordbeg: DEBUG_PRINT1 ("EXECUTING wordbeg.\n"); if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1))) break; goto fail; case wordend: DEBUG_PRINT1 ("EXECUTING wordend.\n"); if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1) && (!WORDCHAR_P (d) || AT_STRINGS_END (d))) break; goto fail; #ifdef emacs case before_dot: DEBUG_PRINT1 ("EXECUTING before_dot.\n"); if (PTR_CHAR_POS ((unsigned char *) d) >= PT) goto fail; break; case at_dot: DEBUG_PRINT1 ("EXECUTING at_dot.\n"); if (PTR_CHAR_POS ((unsigned char *) d) != PT) goto fail; break; case after_dot: DEBUG_PRINT1 ("EXECUTING after_dot.\n"); if (PTR_CHAR_POS ((unsigned char *) d) <= PT) goto fail; break; case syntaxspec: DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt); mcnt = *p++; goto matchsyntax; case wordchar: DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n"); mcnt = (int) Sword; matchsyntax: PREFETCH (); /* Can't use *d++ here; SYNTAX may be an unsafe macro. */ d++; if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt) goto fail; SET_REGS_MATCHED (); break; case notsyntaxspec: DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt); mcnt = *p++; goto matchnotsyntax; case notwordchar: DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n"); mcnt = (int) Sword; matchnotsyntax: PREFETCH (); /* Can't use *d++ here; SYNTAX may be an unsafe macro. */ d++; if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt) goto fail; SET_REGS_MATCHED (); break; #else /* not emacs */ case wordchar: DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n"); PREFETCH (); if (!WORDCHAR_P (d)) goto fail; SET_REGS_MATCHED (); d++; break; case notwordchar: DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n"); PREFETCH (); if (WORDCHAR_P (d)) goto fail; SET_REGS_MATCHED (); d++; break; #endif /* not emacs */ default: abort (); } continue; /* Successfully executed one pattern command; keep going. */ /* We goto here if a matching operation fails. */ fail: if (!FAIL_STACK_EMPTY ()) { /* A restart point is known. Restore to that state. */ DEBUG_PRINT1 ("\nFAIL:\n"); POP_FAILURE_POINT (d, p, lowest_active_reg, highest_active_reg, regstart, regend, reg_info); /* If this failure point is a dummy, try the next one. */ if (!p) goto fail; /* If we failed to the end of the pattern, don't examine *p. */ assert (p <= pend); if (p < pend) { boolean is_a_jump_n = false; /* If failed to a backwards jump that's part of a repetition loop, need to pop this failure point and use the next one. */ switch ((re_opcode_t) *p) { case jump_n: is_a_jump_n = true; case maybe_pop_jump: case pop_failure_jump: case jump: p1 = p + 1; EXTRACT_NUMBER_AND_INCR (mcnt, p1); p1 += mcnt; if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n) || (!is_a_jump_n && (re_opcode_t) *p1 == on_failure_jump)) goto fail; break; default: /* do nothing */ ; } } if (d >= string1 && d <= end1) dend = end_match_1; } else break; /* Matching at this starting point really fails. */ } /* for (;;) */ if (best_regs_set) goto restore_best_regs; FREE_VARIABLES (); return -1; /* Failure to match. */ } /* re_match_2 */ /* Subroutine definitions for re_match_2. */ /* We are passed P pointing to a register number after a start_memory. Return true if the pattern up to the corresponding stop_memory can match the empty string, and false otherwise. If we find the matching stop_memory, sets P to point to one past its number. Otherwise, sets P to an undefined byte less than or equal to END. We don't handle duplicates properly (yet). */ static boolean group_match_null_string_p (p, end, reg_info) unsigned char **p, *end; register_info_type *reg_info; { int mcnt; /* Point to after the args to the start_memory. */ unsigned char *p1 = *p + 2; while (p1 < end) { /* Skip over opcodes that can match nothing, and return true or false, as appropriate, when we get to one that can't, or to the matching stop_memory. */ switch ((re_opcode_t) *p1) { /* Could be either a loop or a series of alternatives. */ case on_failure_jump: p1++; EXTRACT_NUMBER_AND_INCR (mcnt, p1); /* If the next operation is not a jump backwards in the pattern. */ if (mcnt >= 0) { /* Go through the on_failure_jumps of the alternatives, seeing if any of the alternatives cannot match nothing. The last alternative starts with only a jump, whereas the rest start with on_failure_jump and end with a jump, e.g., here is the pattern for `a|b|c': /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3 /exactn/1/c So, we have to first go through the first (n-1) alternatives and then deal with the last one separately. */ /* Deal with the first (n-1) alternatives, which start with an on_failure_jump (see above) that jumps to right past a jump_past_alt. */ while ((re_opcode_t) p1[mcnt-3] == jump_past_alt) { /* `mcnt' holds how many bytes long the alternative is, including the ending `jump_past_alt' and its number. */ if (!alt_match_null_string_p (p1, p1 + mcnt - 3, reg_info)) return false; /* Move to right after this alternative, including the jump_past_alt. */ p1 += mcnt; /* Break if it's the beginning of an n-th alternative that doesn't begin with an on_failure_jump. */ if ((re_opcode_t) *p1 != on_failure_jump) break; /* Still have to check that it's not an n-th alternative that starts with an on_failure_jump. */ p1++; EXTRACT_NUMBER_AND_INCR (mcnt, p1); if ((re_opcode_t) p1[mcnt-3] != jump_past_alt) { /* Get to the beginning of the n-th alternative. */ p1 -= 3; break; } } /* Deal with the last alternative: go back and get number of the `jump_past_alt' just before it. `mcnt' contains the length of the alternative. */ EXTRACT_NUMBER (mcnt, p1 - 2); if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info)) return false; p1 += mcnt; /* Get past the n-th alternative. */ } /* if mcnt > 0 */ break; case stop_memory: assert (p1[1] == **p); *p = p1 + 2; return true; default: if (!common_op_match_null_string_p (&p1, end, reg_info)) return false; } } /* while p1 < end */ return false; } /* group_match_null_string_p */ /* Similar to group_match_null_string_p, but doesn't deal with alternatives: It expects P to be the first byte of a single alternative and END one byte past the last. The alternative can contain groups. */ static boolean alt_match_null_string_p (p, end, reg_info) unsigned char *p, *end; register_info_type *reg_info; { int mcnt; unsigned char *p1 = p; while (p1 < end) { /* Skip over opcodes that can match nothing, and break when we get to one that can't. */ switch ((re_opcode_t) *p1) { /* It's a loop. */ case on_failure_jump: p1++; EXTRACT_NUMBER_AND_INCR (mcnt, p1); p1 += mcnt; break; default: if (!common_op_match_null_string_p (&p1, end, reg_info)) return false; } } /* while p1 < end */ return true; } /* alt_match_null_string_p */ /* Deals with the ops common to group_match_null_string_p and alt_match_null_string_p. Sets P to one after the op and its arguments, if any. */ static boolean common_op_match_null_string_p (p, end, reg_info) unsigned char **p, *end; register_info_type *reg_info; { int mcnt; boolean ret; int reg_no; unsigned char *p1 = *p; switch ((re_opcode_t) *p1++) { case no_op: case begline: case endline: case begbuf: case endbuf: case wordbeg: case wordend: case wordbound: case notwordbound: #ifdef emacs case before_dot: case at_dot: case after_dot: #endif break; case start_memory: reg_no = *p1; assert (reg_no > 0 && reg_no <= MAX_REGNUM); ret = group_match_null_string_p (&p1, end, reg_info); /* Have to set this here in case we're checking a group which contains a group and a back reference to it. */ if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE) REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret; if (!ret) return false; break; /* If this is an optimized succeed_n for zero times, make the jump. */ case jump: EXTRACT_NUMBER_AND_INCR (mcnt, p1); if (mcnt >= 0) p1 += mcnt; else return false; break; case succeed_n: /* Get to the number of times to succeed. */ p1 += 2; EXTRACT_NUMBER_AND_INCR (mcnt, p1); if (mcnt == 0) { p1 -= 4; EXTRACT_NUMBER_AND_INCR (mcnt, p1); p1 += mcnt; } else return false; break; case duplicate: if (!REG_MATCH_NULL_STRING_P (reg_info[*p1])) return false; break; case set_number_at: p1 += 4; default: /* All other opcodes mean we cannot match the empty string. */ return false; } *p = p1; return true; } /* common_op_match_null_string_p */ /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN bytes; nonzero otherwise. */ static int bcmp_translate (s1, s2, len, translate) unsigned char *s1, *s2; register int len; RE_TRANSLATE_TYPE translate; { register unsigned char *p1 = s1, *p2 = s2; while (len) { if (translate[*p1++] != translate[*p2++]) return 1; len--; } return 0; } /* Entry points for GNU code. */ /* re_compile_pattern is the GNU regular expression compiler: it compiles PATTERN (of length SIZE) and puts the result in BUFP. Returns 0 if the pattern was valid, otherwise an error string. Assumes the `allocated' (and perhaps `buffer') and `translate' fields are set in BUFP on entry. We call regex_compile to do the actual compilation. */ const char * re_compile_pattern (pattern, length, bufp) const char *pattern; int length; struct re_pattern_buffer *bufp; { reg_errcode_t ret; /* GNU code is written to assume at least RE_NREGS registers will be set (and at least one extra will be -1). */ bufp->regs_allocated = REGS_UNALLOCATED; /* And GNU code determines whether or not to get register information by passing null for the REGS argument to re_match, etc., not by setting no_sub. */ bufp->no_sub = 0; /* Match anchors at newline. */ bufp->newline_anchor = 1; ret = regex_compile (pattern, length, re_syntax_options, bufp); if (!ret) return NULL; return gettext (re_error_msgid[(int) ret]); } /* Entry points compatible with 4.2 BSD regex library. We don't define them unless specifically requested. */ #if defined (_REGEX_RE_COMP) || defined (_LIBC) /* BSD has one and only one pattern buffer. */ static struct re_pattern_buffer re_comp_buf; char * #ifdef _LIBC /* Make these definitions weak in libc, so POSIX programs can redefine these names if they don't use our functions, and still use regcomp/regexec below without link errors. */ weak_function #endif re_comp (s) const char *s; { reg_errcode_t ret; if (!s) { if (!re_comp_buf.buffer) return gettext ("No previous regular expression"); return 0; } if (!re_comp_buf.buffer) { re_comp_buf.buffer = (unsigned char *) malloc (200); if (re_comp_buf.buffer == NULL) return gettext (re_error_msgid[(int) REG_ESPACE]); re_comp_buf.allocated = 200; re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH); if (re_comp_buf.fastmap == NULL) return gettext (re_error_msgid[(int) REG_ESPACE]); } /* Since `re_exec' always passes NULL for the `regs' argument, we don't need to initialize the pattern buffer fields which affect it. */ /* Match anchors at newlines. */ re_comp_buf.newline_anchor = 1; ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf); if (!ret) return NULL; /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */ return (char *) gettext (re_error_msgid[(int) ret]); } int #ifdef _LIBC weak_function #endif re_exec (s) const char *s; { const int len = strlen (s); return 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0); } #endif /* _REGEX_RE_COMP */ /* POSIX.2 functions. Don't define these for Emacs. */ #ifndef emacs /* regcomp takes a regular expression as a string and compiles it. PREG is a regex_t *. We do not expect any fields to be initialized, since POSIX says we shouldn't. Thus, we set `buffer' to the compiled pattern; `used' to the length of the compiled pattern; `syntax' to RE_SYNTAX_POSIX_EXTENDED if the REG_EXTENDED bit in CFLAGS is set; otherwise, to RE_SYNTAX_POSIX_BASIC; `newline_anchor' to REG_NEWLINE being set in CFLAGS; `fastmap' and `fastmap_accurate' to zero; `re_nsub' to the number of subexpressions in PATTERN. PATTERN is the address of the pattern string. CFLAGS is a series of bits which affect compilation. If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we use POSIX basic syntax. If REG_NEWLINE is set, then . and [^...] don't match newline. Also, regexec will try a match beginning after every newline. If REG_ICASE is set, then we considers upper- and lowercase versions of letters to be equivalent when matching. If REG_NOSUB is set, then when PREG is passed to regexec, that routine will report only success or failure, and nothing about the registers. It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for the return codes and their meanings.) */ int regcomp (preg, pattern, cflags) regex_t *preg; const char *pattern; int cflags; { reg_errcode_t ret; unsigned syntax = (cflags & REG_EXTENDED) ? RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC; /* regex_compile will allocate the space for the compiled pattern. */ preg->buffer = 0; preg->allocated = 0; preg->used = 0; /* Don't bother to use a fastmap when searching. This simplifies the REG_NEWLINE case: if we used a fastmap, we'd have to put all the characters after newlines into the fastmap. This way, we just try every character. */ preg->fastmap = 0; if (cflags & REG_ICASE) { unsigned i; preg->translate = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE * sizeof (*(RE_TRANSLATE_TYPE)0)); if (preg->translate == NULL) return (int) REG_ESPACE; /* Map uppercase characters to corresponding lowercase ones. */ for (i = 0; i < CHAR_SET_SIZE; i++) preg->translate[i] = ISUPPER (i) ? tolower (i) : i; } else preg->translate = NULL; /* If REG_NEWLINE is set, newlines are treated differently. */ if (cflags & REG_NEWLINE) { /* REG_NEWLINE implies neither . nor [^...] match newline. */ syntax &= ~RE_DOT_NEWLINE; syntax |= RE_HAT_LISTS_NOT_NEWLINE; /* It also changes the matching behavior. */ preg->newline_anchor = 1; } else preg->newline_anchor = 0; preg->no_sub = !!(cflags & REG_NOSUB); /* POSIX says a null character in the pattern terminates it, so we can use strlen here in compiling the pattern. */ ret = regex_compile (pattern, strlen (pattern), syntax, preg); /* POSIX doesn't distinguish between an unmatched open-group and an unmatched close-group: both are REG_EPAREN. */ if (ret == REG_ERPAREN) ret = REG_EPAREN; return (int) ret; } /* regexec searches for a given pattern, specified by PREG, in the string STRING. If NMATCH is zero or REG_NOSUB was set in the cflags argument to `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at least NMATCH elements, and we set them to the offsets of the corresponding matched substrings. EFLAGS specifies `execution flags' which affect matching: if REG_NOTBOL is set, then ^ does not match at the beginning of the string; if REG_NOTEOL is set, then $ does not match at the end. We return 0 if we find a match and REG_NOMATCH if not. */ int regexec (preg, string, nmatch, pmatch, eflags) const regex_t *preg; const char *string; size_t nmatch; regmatch_t pmatch[]; int eflags; { int ret; struct re_registers regs; regex_t private_preg; int len = strlen (string); boolean want_reg_info = !preg->no_sub && nmatch > 0; private_preg = *preg; private_preg.not_bol = !!(eflags & REG_NOTBOL); private_preg.not_eol = !!(eflags & REG_NOTEOL); /* The user has told us exactly how many registers to return information about, via `nmatch'. We have to pass that on to the matching routines. */ private_preg.regs_allocated = REGS_FIXED; if (want_reg_info) { regs.num_regs = nmatch; regs.start = TALLOC (nmatch, regoff_t); regs.end = TALLOC (nmatch, regoff_t); if (regs.start == NULL || regs.end == NULL) return (int) REG_NOMATCH; } /* Perform the searching operation. */ ret = re_search (&private_preg, string, len, /* start: */ 0, /* range: */ len, want_reg_info ? ®s : (struct re_registers *) 0); /* Copy the register information to the POSIX structure. */ if (want_reg_info) { if (ret >= 0) { unsigned r; for (r = 0; r < nmatch; r++) { pmatch[r].rm_so = regs.start[r]; pmatch[r].rm_eo = regs.end[r]; } } /* If we needed the temporary register info, free the space now. */ free (regs.start); free (regs.end); } /* We want zero return to mean success, unlike `re_search'. */ return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH; } /* Returns a message corresponding to an error code, ERRCODE, returned from either regcomp or regexec. We don't use PREG here. */ size_t regerror (errcode, preg, errbuf, errbuf_size) int errcode; const regex_t *preg; char *errbuf; size_t errbuf_size; { const char *msg; size_t msg_size; if (errcode < 0 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0]))) /* Only error codes returned by the rest of the code should be passed to this routine. If we are given anything else, or if other regex code generates an invalid error code, then the program has a bug. Dump core so we can fix it. */ abort (); msg = gettext (re_error_msgid[errcode]); msg_size = strlen (msg) + 1; /* Includes the null. */ if (errbuf_size != 0) { if (msg_size > errbuf_size) { strncpy (errbuf, msg, errbuf_size - 1); errbuf[errbuf_size - 1] = 0; } else strcpy (errbuf, msg); } return msg_size; } /* Free dynamically allocated space used by PREG. */ void regfree (preg) regex_t *preg; { if (preg->buffer != NULL) free (preg->buffer); preg->buffer = NULL; preg->allocated = 0; preg->used = 0; if (preg->fastmap != NULL) free (preg->fastmap); preg->fastmap = NULL; preg->fastmap_accurate = 0; if (preg->translate != NULL) free (preg->translate); preg->translate = NULL; } #endif /* not emacs */ clearsilver-0.10.5/util/regex/regex.h0000644001211700116100000004473210261037532014407 00000000000000/* Definitions for data structures and routines for the regular expression library, version 0.12. Copyright (C) 1985, 89, 90, 91, 92, 93, 95 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef __REGEXP_LIBRARY_H__ #define __REGEXP_LIBRARY_H__ /* POSIX says that must be included (by the caller) before . */ #if !defined (_POSIX_C_SOURCE) && !defined (_POSIX_SOURCE) && defined (VMS) /* VMS doesn't have `size_t' in , even though POSIX says it should be there. */ #include #endif /* The following bits are used to determine the regexp syntax we recognize. The set/not-set meanings are chosen so that Emacs syntax remains the value 0. The bits are given in alphabetical order, and the definitions shifted by one from the previous bit; thus, when we add or remove a bit, only one other definition need change. */ typedef unsigned reg_syntax_t; /* If this bit is not set, then \ inside a bracket expression is literal. If set, then such a \ quotes the following character. */ #define RE_BACKSLASH_ESCAPE_IN_LISTS (1) /* If this bit is not set, then + and ? are operators, and \+ and \? are literals. If set, then \+ and \? are operators and + and ? are literals. */ #define RE_BK_PLUS_QM (RE_BACKSLASH_ESCAPE_IN_LISTS << 1) /* If this bit is set, then character classes are supported. They are: [:alpha:], [:upper:], [:lower:], [:digit:], [:alnum:], [:xdigit:], [:space:], [:print:], [:punct:], [:graph:], and [:cntrl:]. If not set, then character classes are not supported. */ #define RE_CHAR_CLASSES (RE_BK_PLUS_QM << 1) /* If this bit is set, then ^ and $ are always anchors (outside bracket expressions, of course). If this bit is not set, then it depends: ^ is an anchor if it is at the beginning of a regular expression or after an open-group or an alternation operator; $ is an anchor if it is at the end of a regular expression, or before a close-group or an alternation operator. This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because POSIX draft 11.2 says that * etc. in leading positions is undefined. We already implemented a previous draft which made those constructs invalid, though, so we haven't changed the code back. */ #define RE_CONTEXT_INDEP_ANCHORS (RE_CHAR_CLASSES << 1) /* If this bit is set, then special characters are always special regardless of where they are in the pattern. If this bit is not set, then special characters are special only in some contexts; otherwise they are ordinary. Specifically, * + ? and intervals are only special when not after the beginning, open-group, or alternation operator. */ #define RE_CONTEXT_INDEP_OPS (RE_CONTEXT_INDEP_ANCHORS << 1) /* If this bit is set, then *, +, ?, and { cannot be first in an re or immediately after an alternation or begin-group operator. */ #define RE_CONTEXT_INVALID_OPS (RE_CONTEXT_INDEP_OPS << 1) /* If this bit is set, then . matches newline. If not set, then it doesn't. */ #define RE_DOT_NEWLINE (RE_CONTEXT_INVALID_OPS << 1) /* If this bit is set, then . doesn't match NUL. If not set, then it does. */ #define RE_DOT_NOT_NULL (RE_DOT_NEWLINE << 1) /* If this bit is set, nonmatching lists [^...] do not match newline. If not set, they do. */ #define RE_HAT_LISTS_NOT_NEWLINE (RE_DOT_NOT_NULL << 1) /* If this bit is set, either \{...\} or {...} defines an interval, depending on RE_NO_BK_BRACES. If not set, \{, \}, {, and } are literals. */ #define RE_INTERVALS (RE_HAT_LISTS_NOT_NEWLINE << 1) /* If this bit is set, +, ? and | aren't recognized as operators. If not set, they are. */ #define RE_LIMITED_OPS (RE_INTERVALS << 1) /* If this bit is set, newline is an alternation operator. If not set, newline is literal. */ #define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1) /* If this bit is set, then `{...}' defines an interval, and \{ and \} are literals. If not set, then `\{...\}' defines an interval. */ #define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1) /* If this bit is set, (...) defines a group, and \( and \) are literals. If not set, \(...\) defines a group, and ( and ) are literals. */ #define RE_NO_BK_PARENS (RE_NO_BK_BRACES << 1) /* If this bit is set, then \ matches . If not set, then \ is a back-reference. */ #define RE_NO_BK_REFS (RE_NO_BK_PARENS << 1) /* If this bit is set, then | is an alternation operator, and \| is literal. If not set, then \| is an alternation operator, and | is literal. */ #define RE_NO_BK_VBAR (RE_NO_BK_REFS << 1) /* If this bit is set, then an ending range point collating higher than the starting range point, as in [z-a], is invalid. If not set, then when ending range point collates higher than the starting range point, the range is ignored. */ #define RE_NO_EMPTY_RANGES (RE_NO_BK_VBAR << 1) /* If this bit is set, then an unmatched ) is ordinary. If not set, then an unmatched ) is invalid. */ #define RE_UNMATCHED_RIGHT_PAREN_ORD (RE_NO_EMPTY_RANGES << 1) /* If this bit is set, succeed as soon as we match the whole pattern, without further backtracking. */ #define RE_NO_POSIX_BACKTRACKING (RE_UNMATCHED_RIGHT_PAREN_ORD << 1) /* This global variable defines the particular regexp syntax to use (for some interfaces). When a regexp is compiled, the syntax used is stored in the pattern buffer, so changing this does not affect already-compiled regexps. */ extern reg_syntax_t re_syntax_options; /* Define combinations of the above bits for the standard possibilities. (The [[[ comments delimit what gets put into the Texinfo file, so don't delete them!) */ /* [[[begin syntaxes]]] */ #define RE_SYNTAX_EMACS 0 #define RE_SYNTAX_AWK \ (RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL \ | RE_NO_BK_PARENS | RE_NO_BK_REFS \ | RE_NO_BK_VBAR | RE_NO_EMPTY_RANGES \ | RE_UNMATCHED_RIGHT_PAREN_ORD) #define RE_SYNTAX_POSIX_AWK \ (RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS) #define RE_SYNTAX_GREP \ (RE_BK_PLUS_QM | RE_CHAR_CLASSES \ | RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS \ | RE_NEWLINE_ALT) #define RE_SYNTAX_EGREP \ (RE_CHAR_CLASSES | RE_CONTEXT_INDEP_ANCHORS \ | RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE \ | RE_NEWLINE_ALT | RE_NO_BK_PARENS \ | RE_NO_BK_VBAR) #define RE_SYNTAX_POSIX_EGREP \ (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES) /* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */ #define RE_SYNTAX_ED RE_SYNTAX_POSIX_BASIC #define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC /* Syntax bits common to both basic and extended POSIX regex syntax. */ #define _RE_SYNTAX_POSIX_COMMON \ (RE_CHAR_CLASSES | RE_DOT_NEWLINE | RE_DOT_NOT_NULL \ | RE_INTERVALS | RE_NO_EMPTY_RANGES) #define RE_SYNTAX_POSIX_BASIC \ (_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM) /* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes RE_LIMITED_OPS, i.e., \? \+ \| are not recognized. Actually, this isn't minimal, since other operators, such as \`, aren't disabled. */ #define RE_SYNTAX_POSIX_MINIMAL_BASIC \ (_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS) #define RE_SYNTAX_POSIX_EXTENDED \ (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \ | RE_CONTEXT_INDEP_OPS | RE_NO_BK_BRACES \ | RE_NO_BK_PARENS | RE_NO_BK_VBAR \ | RE_UNMATCHED_RIGHT_PAREN_ORD) /* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added. */ #define RE_SYNTAX_POSIX_MINIMAL_EXTENDED \ (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS \ | RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES \ | RE_NO_BK_PARENS | RE_NO_BK_REFS \ | RE_NO_BK_VBAR | RE_UNMATCHED_RIGHT_PAREN_ORD) /* [[[end syntaxes]]] */ /* Maximum number of duplicates an interval can allow. Some systems (erroneously) define this in other header files, but we want our value, so remove any previous define. */ #ifdef RE_DUP_MAX #undef RE_DUP_MAX #endif #define RE_DUP_MAX ((1 << 15) - 1) /* POSIX `cflags' bits (i.e., information for `regcomp'). */ /* If this bit is set, then use extended regular expression syntax. If not set, then use basic regular expression syntax. */ #define REG_EXTENDED 1 /* If this bit is set, then ignore case when matching. If not set, then case is significant. */ #define REG_ICASE (REG_EXTENDED << 1) /* If this bit is set, then anchors do not match at newline characters in the string. If not set, then anchors do match at newlines. */ #define REG_NEWLINE (REG_ICASE << 1) /* If this bit is set, then report only success or fail in regexec. If not set, then returns differ between not matching and errors. */ #define REG_NOSUB (REG_NEWLINE << 1) /* POSIX `eflags' bits (i.e., information for regexec). */ /* If this bit is set, then the beginning-of-line operator doesn't match the beginning of the string (presumably because it's not the beginning of a line). If not set, then the beginning-of-line operator does match the beginning of the string. */ #define REG_NOTBOL 1 /* Like REG_NOTBOL, except for the end-of-line. */ #define REG_NOTEOL (1 << 1) /* If any error codes are removed, changed, or added, update the `re_error_msg' table in regex.c. */ typedef enum { REG_NOERROR = 0, /* Success. */ REG_NOMATCH, /* Didn't find a match (for regexec). */ /* POSIX regcomp return error codes. (In the order listed in the standard.) */ REG_BADPAT, /* Invalid pattern. */ REG_ECOLLATE, /* Not implemented. */ REG_ECTYPE, /* Invalid character class name. */ REG_EESCAPE, /* Trailing backslash. */ REG_ESUBREG, /* Invalid back reference. */ REG_EBRACK, /* Unmatched left bracket. */ REG_EPAREN, /* Parenthesis imbalance. */ REG_EBRACE, /* Unmatched \{. */ REG_BADBR, /* Invalid contents of \{\}. */ REG_ERANGE, /* Invalid range end. */ REG_ESPACE, /* Ran out of memory. */ REG_BADRPT, /* No preceding re for repetition op. */ /* Error codes we've added. */ REG_EEND, /* Premature end. */ REG_ESIZE, /* Compiled pattern bigger than 2^16 bytes. */ REG_ERPAREN /* Unmatched ) or \); not returned from regcomp. */ } reg_errcode_t; /* This data structure represents a compiled pattern. Before calling the pattern compiler, the fields `buffer', `allocated', `fastmap', `translate', and `no_sub' can be set. After the pattern has been compiled, the `re_nsub' field is available. All other fields are private to the regex routines. */ #ifndef RE_TRANSLATE_TYPE #define RE_TRANSLATE_TYPE char * #endif struct re_pattern_buffer { /* [[[begin pattern_buffer]]] */ /* Space that holds the compiled pattern. It is declared as `unsigned char *' because its elements are sometimes used as array indexes. */ unsigned char *buffer; /* Number of bytes to which `buffer' points. */ unsigned long allocated; /* Number of bytes actually used in `buffer'. */ unsigned long used; /* Syntax setting with which the pattern was compiled. */ reg_syntax_t syntax; /* Pointer to a fastmap, if any, otherwise zero. re_search uses the fastmap, if there is one, to skip over impossible starting points for matches. */ char *fastmap; /* Either a translate table to apply to all characters before comparing them, or zero for no translation. The translation is applied to a pattern when it is compiled and to a string when it is matched. */ RE_TRANSLATE_TYPE translate; /* Number of subexpressions found by the compiler. */ size_t re_nsub; /* Zero if this pattern cannot match the empty string, one else. Well, in truth it's used only in `re_search_2', to see whether or not we should use the fastmap, so we don't set this absolutely perfectly; see `re_compile_fastmap' (the `duplicate' case). */ unsigned can_be_null : 1; /* If REGS_UNALLOCATED, allocate space in the `regs' structure for `max (RE_NREGS, re_nsub + 1)' groups. If REGS_REALLOCATE, reallocate space if necessary. If REGS_FIXED, use what's there. */ #define REGS_UNALLOCATED 0 #define REGS_REALLOCATE 1 #define REGS_FIXED 2 unsigned regs_allocated : 2; /* Set to zero when `regex_compile' compiles a pattern; set to one by `re_compile_fastmap' if it updates the fastmap. */ unsigned fastmap_accurate : 1; /* If set, `re_match_2' does not return information about subexpressions. */ unsigned no_sub : 1; /* If set, a beginning-of-line anchor doesn't match at the beginning of the string. */ unsigned not_bol : 1; /* Similarly for an end-of-line anchor. */ unsigned not_eol : 1; /* If true, an anchor at a newline matches. */ unsigned newline_anchor : 1; /* [[[end pattern_buffer]]] */ }; typedef struct re_pattern_buffer regex_t; /* Type for byte offsets within the string. POSIX mandates this. */ typedef int regoff_t; /* This is the structure we store register match data in. See regex.texinfo for a full description of what registers match. */ struct re_registers { unsigned num_regs; regoff_t *start; regoff_t *end; }; /* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer, `re_match_2' returns information about at least this many registers the first time a `regs' structure is passed. */ #ifndef RE_NREGS #define RE_NREGS 30 #endif /* POSIX specification for registers. Aside from the different names than `re_registers', POSIX uses an array of structures, instead of a structure of arrays. */ typedef struct { regoff_t rm_so; /* Byte offset from string's start to substring's start. */ regoff_t rm_eo; /* Byte offset from string's start to substring's end. */ } regmatch_t; /* Declarations for routines. */ /* To avoid duplicating every routine declaration -- once with a prototype (if we are ANSI), and once without (if we aren't) -- we use the following macro to declare argument types. This unfortunately clutters up the declarations a bit, but I think it's worth it. */ #if __STDC__ #define _RE_ARGS(args) args #else /* not __STDC__ */ #define _RE_ARGS(args) () #endif /* not __STDC__ */ /* Sets the current default syntax to SYNTAX, and return the old syntax. You can also simply assign to the `re_syntax_options' variable. */ extern reg_syntax_t re_set_syntax _RE_ARGS ((reg_syntax_t syntax)); /* Compile the regular expression PATTERN, with length LENGTH and syntax given by the global `re_syntax_options', into the buffer BUFFER. Return NULL if successful, and an error string if not. */ extern const char *re_compile_pattern _RE_ARGS ((const char *pattern, int length, struct re_pattern_buffer *buffer)); /* Compile a fastmap for the compiled pattern in BUFFER; used to accelerate searches. Return 0 if successful and -2 if was an internal error. */ extern int re_compile_fastmap _RE_ARGS ((struct re_pattern_buffer *buffer)); /* Search in the string STRING (with length LENGTH) for the pattern compiled into BUFFER. Start searching at position START, for RANGE characters. Return the starting position of the match, -1 for no match, or -2 for an internal error. Also return register information in REGS (if REGS and BUFFER->no_sub are nonzero). */ extern int re_search _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string, int length, int start, int range, struct re_registers *regs)); /* Like `re_search', but search in the concatenation of STRING1 and STRING2. Also, stop searching at index START + STOP. */ extern int re_search_2 _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string1, int length1, const char *string2, int length2, int start, int range, struct re_registers *regs, int stop)); /* Like `re_search', but return how many characters in STRING the regexp in BUFFER matched, starting at position START. */ extern int re_match _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string, int length, int start, struct re_registers *regs)); /* Relates to `re_match' as `re_search_2' relates to `re_search'. */ extern int re_match_2 _RE_ARGS ((struct re_pattern_buffer *buffer, const char *string1, int length1, const char *string2, int length2, int start, struct re_registers *regs, int stop)); /* Set REGS to hold NUM_REGS registers, storing them in STARTS and ENDS. Subsequent matches using BUFFER and REGS will use this memory for recording register information. STARTS and ENDS must be allocated with malloc, and must each be at least `NUM_REGS * sizeof (regoff_t)' bytes long. If NUM_REGS == 0, then subsequent matches should allocate their own register data. Unless this function is called, the first search or match using PATTERN_BUFFER will allocate its own register data, without freeing the old data. */ extern void re_set_registers _RE_ARGS ((struct re_pattern_buffer *buffer, struct re_registers *regs, unsigned num_regs, regoff_t *starts, regoff_t *ends)); #ifdef _REGEX_RE_COMP /* 4.2 bsd compatibility. */ extern char *re_comp _RE_ARGS ((const char *)); extern int re_exec _RE_ARGS ((const char *)); #endif /* POSIX compatibility. */ extern int regcomp _RE_ARGS ((regex_t *preg, const char *pattern, int cflags)); extern int regexec _RE_ARGS ((const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags)); extern size_t regerror _RE_ARGS ((int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)); extern void regfree _RE_ARGS ((regex_t *preg)); #endif /* not __REGEXP_LIBRARY_H__ */ /* Local variables: make-backup-files: t version-control: t trim-versions-without-asking: nil End: */ clearsilver-0.10.5/util/skiplist.c0000644001211700116100000003743710261037532014024 00000000000000/* * * Thread-safe Skiplist Using Integer Identifiers * Copyright 1998-2000 Scott Shambarger (scott@shambarger.net) * * This software is open source. Permission to use, copy, modify, and * distribute this software for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies. No * warranty of any kind is expressed or implied. Use at your own risk. * * 1/14/2001 blong * Made it use neo errs... probably need to check locking functions * for error returns... * */ #include "cs_config.h" #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "skiplist.h" #include "ulocks.h" typedef struct skipItem *skipItem; /* structure is sized on allocation based on its level */ struct skipItem { UINT32 locks; /* count of locks on value */ UINT32 key; /* item's key */ void *value; /* item's value */ INT32 level; /* item level */ skipItem next[1]; /* array of next items */ }; #define SIZEOFITEM(max) (sizeof(struct skipItem) + \ ((max+1) * sizeof(skipItem))) struct skipList_struct { INT32 topLevel; /* current max level in any item */ INT32 levelHint; /* hint at level to start search */ skipItem header; /* header item (has all levels) */ skipItem tail; /* tail item (has all levels) */ /* elements to handle cached deleted items */ skipItem deleted; /* cached deleted items (linked by level+1 next entries) */ UINT32 cached; /* number of cached deleted items */ int flushing; /* TRUE if thread waiting to flush cached items */ UINT32 readers; /* number of current readers */ int block; /* TRUE if readers should wait */ pthread_mutex_t read; /* readers count/cond wait mutex */ pthread_mutex_t write; /* writer mutex */ pthread_cond_t resume; /* condition to wait on to resume reads */ pthread_cond_t flush; /* condition to wait on for flush */ /* list constants */ int threaded; /* TRUE if list needs to be thread safe */ UINT32 flushLimit; /* max number of cached deleted items before flush */ INT32 maxLevel; /* max level list can reach */ double randLimit; /* min random value to jump levels */ skipFreeValue freeValue; /* free value callback */ void *freeValueCtx; /* context to pass to callback */ }; static void readLock(skipList list) { mLock(&list->read); if(list->block) cWait(&list->resume, &list->read); list->readers++; mUnlock(&list->read); return; } static void readUnlock(skipList list, skipItem x, void **plock) { int startFlush = FALSE; if(list->threaded) mLock(&list->read); if(plock) { x->locks++; *plock = x; } if(! list->threaded) return; list->readers--; if((list->readers == 0) && list->block) startFlush = TRUE; mUnlock(&list->read); if(startFlush) cSignal(&list->flush); return; } static void readBlock(skipList list) { mLock(&list->read); list->block = TRUE; if(list->readers) cWait(&list->flush, &list->read); /* wait until reader locks released */ return; } static void readUnblock(skipList list) { list->block = FALSE; mUnlock(&list->read); cBroadcast(&list->resume); return; } static void writeLock(skipList list) { mLock(&list->write); return; } static void writeUnlock(skipList list) { mUnlock(&list->write); return; } static NEOERR *skipAllocItem(skipItem *item, UINT32 level, UINT32 key, void *value) { if(! (*item = malloc(SIZEOFITEM(level)))) return nerr_raise(NERR_NOMEM, "Unable to allocate space for skipItem"); /* init new item */ (*item)->locks = 0; (*item)->key = key; (*item)->value = value; (*item)->level = level; return STATUS_OK; } static void skipFreeItem(skipList list, skipItem item) { if(list->freeValue) list->freeValue(item->value, list->freeValueCtx); /* free value */ free(item); /* release item */ return; } static void skipFlushDeleted(skipList list, int force) { skipItem x, y, next; x = list->deleted; y = x->next[x->level + 1]; while(y != list->tail) { next = y->next[y->level + 1]; if(force || (! y->locks)) { /* check if value currently locked */ x->next[x->level + 1] = next; /* set previous item's next link */ skipFreeItem(list, y); /* free item */ list->cached--; /* update cached count */ } else { x = y; /* make this item the previous item */ } y = next; /* advance to next item */ } return; } static void skipWriteUnlock(skipList list) { int flush; if(! list->threaded) return; if((list->cached > list->flushLimit) && (! list->flushing)) { list->flushing = TRUE; flush = TRUE; } else { flush = FALSE; } writeUnlock(list); /* let any pending writes complete */ readUnlock(list, NULL, NULL); /* no longer reading */ if(flush) { /* we are now flushing deleted items */ readBlock(list); /* acquire all read locks */ /* at this point no readers/writers are active */ skipFlushDeleted(list, FALSE); /* flush deleted items */ list->flushing = FALSE; /* done flushing */ readUnblock(list); /* let everyone continue */ } return; } static skipItem skipFind(skipList list, UINT32 key) { skipItem x, y = NULL; INT32 i; if(list->threaded) readLock(list); x = list->header; /* header contains all levels */ for(i = list->levelHint; /* loop from levelHint level down to level 0 */ i >= 0; i--) { y = x->next[i]; /* get next item at new level */ while(y->key < key) { /* if y has a smaller key, try the next item */ x = y; /* save x in case we overshoot */ y = x->next[i]; /* get next item */ } } return y; } void *skipSearch(skipList list, UINT32 key, void **plock) { skipItem y; void *value; y = skipFind(list, key); /* find item */ if(y->key == key) { /* y has our key, or it isn't here */ value = y->value; } else { /* didn't find item, don't allow locks */ value = NULL; plock = NULL; } readUnlock(list, y, plock); return value; } void *skipNext(skipList list, UINT32 *pkey, void **plock) { skipItem y; void *value; y = skipFind(list, *pkey); /* find item */ if((y->key == *pkey) && (y != list->tail)) /* skip to next if found y */ y = y->next[0]; if(y != list->tail) { /* reset key to next, return value */ *pkey = y->key; value = y->value; } else { /* no next item, don't allow locks */ value = NULL; plock = NULL; } readUnlock(list, y, plock); return value; } void skipRelease(skipList list, void *lock) { skipItem x; mLock(&list->read); x = lock; x->locks--; mUnlock(&list->read); return; } /* list is write locked */ static NEOERR *skipNewItem(skipList list, skipItem *item, UINT32 key, void *value) { INT32 level = 0; while((drand48() < list->randLimit) && (level < list->maxLevel)) level++; if(level > list->topLevel) { if(list->topLevel < list->maxLevel) list->topLevel++; level = list->topLevel; } return skipAllocItem(item, level, key, value); } /* list is write locked */ static void skipDeleteItem(skipList list, skipItem item) { if(list->threaded) { item->next[item->level + 1] = list->deleted->next[1]; list->cached++; list->deleted->next[1] = item; } else { skipFreeItem(list, item); } return; } NEOERR *skipNewList(skipList *skip, int threaded, int root, int maxLevel, int flushLimit, skipFreeValue freeValue, void *ctx) { NEOERR *err; skipList list; UINT32 i; *skip = NULL; if(! (list = calloc(1, sizeof(struct skipList_struct)))) return nerr_raise(NERR_NOMEM, "Unable to allocate memore for skiplist"); if (maxLevel == 0) return nerr_raise(NERR_ASSERT, "maxLevel must be greater than 0"); if(maxLevel >= SKIP_MAXLEVEL) /* check limits */ maxLevel = SKIP_MAXLEVEL-1; if(root > 4) root = 4; else if(root < 2) root = 2; list->maxLevel = maxLevel; /* init list constants */ list->randLimit = 1.0 / (double)root; list->threaded = threaded; list->freeValue = freeValue; list->freeValueCtx = ctx; do { if(threaded) { list->flushLimit = flushLimit; err = mCreate(&list->read); if (err != STATUS_OK) break; err = mCreate(&list->write); if (err != STATUS_OK) break; err = cCreate(&list->resume); if (err != STATUS_OK) break; err = cCreate(&list->flush); if (err != STATUS_OK) break; } err = skipAllocItem(&(list->header), list->maxLevel, 0, NULL); if (err != STATUS_OK) break; err = skipAllocItem(&(list->tail), list->maxLevel, (UINT32)-1, NULL); if (err != STATUS_OK) break; err = skipAllocItem(&(list->deleted), 0, 0, NULL); if (err != STATUS_OK) break; for(i = 0; /* init header and tail */ i <= list->maxLevel; i++) { list->tail->next[i] = NULL; list->header->next[i] = list->tail; } list->deleted->next[1] = list->tail; *skip = list; return STATUS_OK; /* return new list */ } while(FALSE); if(list->header) /* failed to make list, bail */ free(list->header); free(list); return nerr_pass(err); } /* list considered locked */ static void skipFreeAllItems(skipList list) { UINT32 i; skipItem x, y; x = list->header->next[0]; while(x != list->tail) { y = x->next[0]; /* get next item from level 0 pointer */ skipFreeItem(list, x); /* release item */ x = y; } /* clear header pointers */ for(i = 0; i <= list->maxLevel; i++) list->header->next[i] = list->tail; return; } void skipFreeList(skipList list) { skipFlushDeleted(list, TRUE); /* flush deleted items */ skipFreeAllItems(list); /* free list items */ if(list->threaded) { cDestroy(&list->flush); cDestroy(&list->resume); mDestroy(&list->write); mDestroy(&list->read); } free(list->tail); /* free list */ free(list->header); free(list->deleted); free(list); return; } /* is locked, is at least level , and ->key < */ static skipItem skipClosest(skipItem x, UINT32 key, UINT32 level) { skipItem y; y = x->next[level]; /* get next item at this level */ while(y->key < key) { /* ensure that we have the item before the key */ x = y; y = x->next[level]; } return x; } static skipItem skipLock(skipList list, UINT32 key, skipItem *save, INT32 top) { INT32 i; skipItem x, y; if(list->threaded) readLock(list); x = list->header; /* header contains all levels */ for(i = top; /* loop from top level down to level 0 */ i >= 0; i--) { y = x->next[i]; /* get next item at this level */ while(y->key < key) { /* if y has a smaller key, try the next item */ x = y; /* save x in case we overshoot */ y = x->next[i]; /* get next item */ } save[i] = x; /* preserve item with next pointer in save */ } if(list->threaded) writeLock(list); /* lock list for update */ /* validate we have the closest previous item */ return skipClosest(x, key, 0); } NEOERR *skipInsert(skipList list, UINT32 key, void *value, int allowUpdate) { NEOERR *err; INT32 i, level; skipItem save[SKIP_MAXLEVEL]; skipItem x, y; if (value == 0) return nerr_raise(NERR_ASSERT, "value must be non-zero"); if (key == 0 || key == (UINT32)-1) return nerr_raise(NERR_ASSERT, "key must not be 0 or -1"); level = list->levelHint; x = skipLock(list, key, save, level); /* quick search for key */ y = x->next[0]; if(y->key == key) { if(!allowUpdate) { skipWriteUnlock(list); return nerr_raise(NERR_DUPLICATE, "key %u exists in skiplist", key); } y->value = value; /* found the key, update value */ skipWriteUnlock(list); return STATUS_OK; } err = skipNewItem(list, &y, key, value); if (err != STATUS_OK) { skipWriteUnlock(list); return nerr_pass(err); } for(i = level + 1; /* is new item has more levels than */ i <= y->level; /* if so fill in save */ i++) save[i] = list->header; for(i = 0; /* populate pointers for all levels */ i <= y->level; i++) { if(i) /* check that save is correct for each level */ x = skipClosest(save[i], key, i); y->next[i] = x->next[i]; /* now insert the item at this level */ x->next[i] = y; /* (order here important for thread-safeness) */ } while((list->levelHint < list->topLevel) /* update levelHint */ && (list->header->next[list->levelHint+1] != list->tail)) list->levelHint++; skipWriteUnlock(list); return STATUS_OK; } void skipDelete(skipList list, UINT32 key) { INT32 i, level; skipItem save[SKIP_MAXLEVEL]; skipItem x, y; assert(key && (key != (UINT32)-1)); level = list->levelHint; x = skipLock(list, key, save, level); /* quick search for key */ y = x->next[0]; /* check that we found the key, and it isn't deleted */ if((y->key != key) || (y->next[0]->key < key)) { skipWriteUnlock(list); return; } for(i = level + 1; /* check if item has more levels than */ i <= y->level; /* if so fill in save */ i++) save[i] = list->header; for(i = y->level; i >= 0; i--) { /* check that save is correct for each level */ x = skipClosest(save[i], key, i); x->next[i] = y->next[i]; /* now remove item at this level */ y->next[i] = x; /* (order here is imported for thread-safeness) */ } skipDeleteItem(list, y); /* put on deleted list */ while((list->levelHint > 0) /* update levelHint */ && (list->header->next[list->levelHint] == list->tail)) list->levelHint--; skipWriteUnlock(list); return; } clearsilver-0.10.5/util/skiplist.h0000644001211700116100000001414710261037532014022 00000000000000/* * * Thread-safe Skiplist Using Integer Identifiers * Copyright 1998-2000 Scott Shambarger (scott@shambarger.net) * * This software is open source. Permission to use, copy, modify, and * distribute this software for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies. No * warranty of any kind is expressed or implied. Use at your own risk. * * 1/14/2001 blong * Made it use neo errs... probably need to check locking functions * for error returns... * */ #ifndef __SKIPLIST_H_ #define __SKIPLIST_H_ #include "util/neo_err.h" __BEGIN_DECLS /* * Larger values of means fewer levels and faster lookups, * but more variability in those lookup times (range limited from 2 to 4). * * should be calculated from expected list size using (^ = power): * * ^ == expected # of items * * I've capped at 20, which would be good for a minimum of * 1 million items on lists with == 2. * * * Example * skipNewList(&(my_wdb->ondisk), 0, 4, 2, 0, NULL, NULL); */ #define SKIP_MAXLEVEL 20 /* SKIP LIST TYPEDEFS */ typedef struct skipList_struct *skipList; typedef void (*skipFreeValue)(void *value, void *ctx); NEOERR *skipNewList(skipList *skip, int threaded, int root, int maxLevel, int flushLimit, skipFreeValue freeValue, void *ctx); /* * Function: skipNewList - create a skip list. * Description: Returns a new skip list. If is true, list is * multi-thread safe. and determine * performance and expected size (see discussion above). * is for threaded lists and determines the * maximum number of deleted items to keep cached during * concurrent searches. Once the limit is reached, new * concurrent reads are blocked until all deleted items are * flushed. * Input: threaded - true if list should be thread-safe. * root - performance parameter (see above). * maxLevel - performance parameter (see above). * flushLimit - max deleted items to keep cached before * forcing a flush. * freeValue - callback made whenever a value is flushed. * ctx - context to pass to . * Output: None. * Return: New skip list, NULL on error. * MT-Level: Safe. */ void skipFreeList(skipList list); /* * Function: skipFreeList - free a skip list. * Description: Release all resources used by including all key/value * pairs. * Input: list - list to free. * Output: None. * Return: None. * MT-Level: Safe for unique . */ void *skipNext(skipList list, UINT32 *pkey, void **plock); /* * Function: skipNext - find next item. * Description: Searches in list for item with key next larger * that the one in , and returns its value if * found, or NULL if not. If is non-NULL, then * the lock returned in will be associated with * the returned value. Until this lock is passed to * skipRelease(), the value will not be freed with the * freeValue callback (see skipNewList()). * Input: list - list to search in. * pkey - pointer to previous key (0 to start). * plock - place for value lock (or NULL). * Output: pkey - set to new key. * plock - set to value lock. * Return: Value associated with new , or NULL last item. * MT-Level: Safe if thread-safe. */ void *skipSearch(skipList list, UINT32 key, void **plock); /* * Function: skipSearch - search a skip list. * Description: Searches for in , and returns value if * found, or NULL if not. If is non-NULL, then * the lock returned in will be associated with * the returned value. Until this lock is passed to * skipRelease(), the value will not be freed with the * freeValue callback (see skipNewList()). * Input: list - list to search in. * key - key to look for. * plock - place for value lock (or NULL). * Output: plock - set to value lock. * Return: Value associated with , or NULL if not found. * MT-Level: Safe if thread-safe. */ void skipRelease(skipList list, void *lock); /* * Function: skipRelease - release lock on value. * Description: Releases the lock on the value associated with . Once * the lock is released, the freeValue callback can be called * and the item freed (see skipNewList()). * Input: list - list containing value to release. * lock - lock to release. * Output: None. * Return: None. * MT-Level: Safe if thread-safe. */ NEOERR *skipInsert(skipList list, UINT32 key, void *value, int allowUpdate); /* * Function: skipInsert - insert an item. * Description: Inserts the / pair into the . * Key values 0 and -1 are reserved (and illegal). * If key is already in list, and is true, * value is updated, otherwise SKIPERR_EXISTS is returned. * Input: list - list to add pair to. * key - key identifying . * value - value to store (may NOT be NULL) * Output: None. * Return: NERR_ASSERT on invalid key or value * NERR_DUPLICATE if allowUpdate is 0 and key exists * NERR_NOMEM * MT-Level: Safe if thread-safe. */ void skipDelete(skipList list, UINT32 key); /* * Function: skipDelete - delete an item. * Description: Delete the item associated with from . * Input: list - list to delete item from. * key - key identifying value to delete. * Output: None. * Return: None. * MT-Level: Safe if thread-safe. */ __END_DECLS #endif /* __SKIPLIST_H_ */ clearsilver-0.10.5/util/snprintf.c0000644001211700116100000004531210261037532014014 00000000000000/* * Copyright Patrick Powell 1995 * This code is based on code written by Patrick Powell (papowell@astart.com) * It may be used for any purpose as long as this notice remains intact * on all source code distributions */ /************************************************************** * Original: * Patrick Powell Tue Apr 11 09:48:21 PDT 1995 * A bombproof version of doprnt (dopr) included. * Sigh. This sort of thing is always nasty do deal with. Note that * the version here does not include floating point... * * snprintf() is used instead of sprintf() as it does limit checks * for string length. This covers a nasty loophole. * * The other functions are there to prevent NULL pointers from * causing nast effects. * * More Recently: * Brandon Long 9/15/96 for mutt 0.43 * This was ugly. It is still ugly. I opted out of floating point * numbers, but the formatter understands just about everything * from the normal C string format, at least as far as I can tell from * the Solaris 2.5 printf(3S) man page. * * Brandon Long 10/22/97 for mutt 0.87.1 * Ok, added some minimal floating point support, which means this * probably requires libm on most operating systems. Don't yet * support the exponent (e,E) and sigfig (g,G). Also, fmtint() * was pretty badly broken, it just wasn't being exercised in ways * which showed it, so that's been fixed. Also, formated the code * to mutt conventions, and removed dead code left over from the * original. Also, there is now a builtin-test, just compile with: * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm * and run snprintf for results. * * Thomas Roessler 01/27/98 for mutt 0.89i * The PGP code was using unsigned hexadecimal formats. * Unfortunately, unsigned formats simply didn't work. * * Michael Elkins 03/05/98 for mutt 0.90.8 * The original code assumed that both snprintf() and vsnprintf() were * missing. Some systems only have snprintf() but not vsnprintf(), so * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF. * * Andrew Tridgell (tridge@samba.org) Oct 1998 * fixed handling of %.0f * added test for HAVE_LONG_DOUBLE * * Russ Allbery 2000-08-26 * fixed return value to comply with C99 * fixed handling of snprintf(NULL, ...) * **************************************************************/ #include "cs_config.h" #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF) #include #include #include /* Define this as a fall through, HAVE_STDARG_H is probably already set */ #define HAVE_VARARGS_H /* varargs declarations: */ #if defined(HAVE_STDARG_H) # include # define HAVE_STDARGS /* let's hope that works everywhere (mj) */ # define VA_LOCAL_DECL va_list ap # define VA_START(f) va_start(ap, f) # define VA_SHIFT(v,t) ; /* no-op for ANSI */ # define VA_END va_end(ap) #else # if defined(HAVE_VARARGS_H) # include # undef HAVE_STDARGS # define VA_LOCAL_DECL va_list ap # define VA_START(f) va_start(ap) /* f is ignored! */ # define VA_SHIFT(v,t) v = va_arg(ap,t) # define VA_END va_end(ap) # else /*XX ** NO VARARGS ** XX*/ # endif #endif #ifdef HAVE_LONG_DOUBLE #define LDOUBLE long double #else #define LDOUBLE double #endif int snprintf (char *str, size_t count, const char *fmt, ...); int vsnprintf (char *str, size_t count, const char *fmt, va_list arg); static int dopr (char *buffer, size_t maxlen, const char *format, va_list args); static int fmtstr (char *buffer, size_t *currlen, size_t maxlen, char *value, int flags, int min, int max); static int fmtint (char *buffer, size_t *currlen, size_t maxlen, long value, int base, int min, int max, int flags); static int fmtfp (char *buffer, size_t *currlen, size_t maxlen, LDOUBLE fvalue, int min, int max, int flags); static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c ); /* * dopr(): poor man's version of doprintf */ /* format read states */ #define DP_S_DEFAULT 0 #define DP_S_FLAGS 1 #define DP_S_MIN 2 #define DP_S_DOT 3 #define DP_S_MAX 4 #define DP_S_MOD 5 #define DP_S_CONV 6 #define DP_S_DONE 7 /* format flags - Bits */ #define DP_F_MINUS (1 << 0) #define DP_F_PLUS (1 << 1) #define DP_F_SPACE (1 << 2) #define DP_F_NUM (1 << 3) #define DP_F_ZERO (1 << 4) #define DP_F_UP (1 << 5) #define DP_F_UNSIGNED (1 << 6) /* Conversion Flags */ #define DP_C_SHORT 1 #define DP_C_LONG 2 #define DP_C_LDOUBLE 3 #define char_to_int(p) (p - '0') #define MAX(p,q) ((p >= q) ? p : q) #define MIN(p,q) ((p <= q) ? p : q) static int dopr (char *buffer, size_t maxlen, const char *format, va_list args) { char ch; long value; LDOUBLE fvalue; char *strvalue; int min; int max; int state; int flags; int cflags; int total; size_t currlen; state = DP_S_DEFAULT; currlen = flags = cflags = min = 0; max = -1; ch = *format++; total = 0; while (state != DP_S_DONE) { if (ch == '\0') state = DP_S_DONE; switch(state) { case DP_S_DEFAULT: if (ch == '%') state = DP_S_FLAGS; else total += dopr_outch (buffer, &currlen, maxlen, ch); ch = *format++; break; case DP_S_FLAGS: switch (ch) { case '-': flags |= DP_F_MINUS; ch = *format++; break; case '+': flags |= DP_F_PLUS; ch = *format++; break; case ' ': flags |= DP_F_SPACE; ch = *format++; break; case '#': flags |= DP_F_NUM; ch = *format++; break; case '0': flags |= DP_F_ZERO; ch = *format++; break; default: state = DP_S_MIN; break; } break; case DP_S_MIN: if (isdigit(ch)) { min = 10*min + char_to_int (ch); ch = *format++; } else if (ch == '*') { min = va_arg (args, int); ch = *format++; state = DP_S_DOT; } else state = DP_S_DOT; break; case DP_S_DOT: if (ch == '.') { state = DP_S_MAX; ch = *format++; } else state = DP_S_MOD; break; case DP_S_MAX: if (isdigit(ch)) { if (max < 0) max = 0; max = 10*max + char_to_int (ch); ch = *format++; } else if (ch == '*') { max = va_arg (args, int); ch = *format++; state = DP_S_MOD; } else state = DP_S_MOD; break; case DP_S_MOD: /* Currently, we don't support Long Long, bummer */ switch (ch) { case 'h': cflags = DP_C_SHORT; ch = *format++; break; case 'l': cflags = DP_C_LONG; ch = *format++; break; case 'L': cflags = DP_C_LDOUBLE; ch = *format++; break; default: break; } state = DP_S_CONV; break; case DP_S_CONV: switch (ch) { case 'd': case 'i': if (cflags == DP_C_SHORT) value = va_arg (args, short int); else if (cflags == DP_C_LONG) value = va_arg (args, long int); else value = va_arg (args, int); total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'o': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) value = va_arg (args, unsigned short int); else if (cflags == DP_C_LONG) value = va_arg (args, unsigned long int); else value = va_arg (args, unsigned int); total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags); break; case 'u': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) value = va_arg (args, unsigned short int); else if (cflags == DP_C_LONG) value = va_arg (args, unsigned long int); else value = va_arg (args, unsigned int); total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'X': flags |= DP_F_UP; case 'x': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) value = va_arg (args, unsigned short int); else if (cflags == DP_C_LONG) value = va_arg (args, unsigned long int); else value = va_arg (args, unsigned int); total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags); break; case 'f': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); else fvalue = va_arg (args, double); /* um, floating point? */ total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags); break; case 'E': flags |= DP_F_UP; case 'e': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); else fvalue = va_arg (args, double); break; case 'G': flags |= DP_F_UP; case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); else fvalue = va_arg (args, double); break; case 'c': total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int)); break; case 's': strvalue = va_arg (args, char *); total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max); break; case 'p': strvalue = va_arg (args, void *); total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags); break; case 'n': if (cflags == DP_C_SHORT) { short int *num; num = va_arg (args, short int *); *num = currlen; } else if (cflags == DP_C_LONG) { long int *num; num = va_arg (args, long int *); *num = currlen; } else { int *num; num = va_arg (args, int *); *num = currlen; } break; case '%': total += dopr_outch (buffer, &currlen, maxlen, ch); break; case 'w': /* not supported yet, treat as next char */ ch = *format++; break; default: /* Unknown, skip */ break; } ch = *format++; state = DP_S_DEFAULT; flags = cflags = min = 0; max = -1; break; case DP_S_DONE: break; default: /* hmm? */ break; /* some picky compilers need this */ } } if (buffer != NULL) { if (currlen < maxlen - 1) buffer[currlen] = '\0'; else buffer[maxlen - 1] = '\0'; } return total; } static int fmtstr (char *buffer, size_t *currlen, size_t maxlen, char *value, int flags, int min, int max) { int padlen, strln; /* amount to pad */ int cnt = 0; int total = 0; if (value == 0) { value = ""; } for (strln = 0; value[strln]; ++strln); /* strlen */ if (max >= 0 && max < strln) strln = max; padlen = min - strln; if (padlen < 0) padlen = 0; if (flags & DP_F_MINUS) padlen = -padlen; /* Left Justify */ while (padlen > 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); --padlen; } while (*value && ((max < 0) || (cnt < max))) { total += dopr_outch (buffer, currlen, maxlen, *value++); ++cnt; } while (padlen < 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); ++padlen; } return total; } /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */ static int fmtint (char *buffer, size_t *currlen, size_t maxlen, long value, int base, int min, int max, int flags) { int signvalue = 0; unsigned long uvalue; char convert[20]; int place = 0; int spadlen = 0; /* amount to space pad */ int zpadlen = 0; /* amount to zero pad */ int caps = 0; int total = 0; if (max < 0) max = 0; uvalue = value; if(!(flags & DP_F_UNSIGNED)) { if( value < 0 ) { signvalue = '-'; uvalue = -value; } else if (flags & DP_F_PLUS) /* Do a sign (+/i) */ signvalue = '+'; else if (flags & DP_F_SPACE) signvalue = ' '; } if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */ do { convert[place++] = (caps? "0123456789ABCDEF":"0123456789abcdef") [uvalue % (unsigned)base ]; uvalue = (uvalue / (unsigned)base ); } while(uvalue && (place < 20)); if (place == 20) place--; convert[place] = 0; zpadlen = max - place; spadlen = min - MAX (max, place) - (signvalue ? 1 : 0); if (zpadlen < 0) zpadlen = 0; if (spadlen < 0) spadlen = 0; if (flags & DP_F_ZERO) { zpadlen = MAX(zpadlen, spadlen); spadlen = 0; } if (flags & DP_F_MINUS) spadlen = -spadlen; /* Left Justifty */ #ifdef DEBUG_SNPRINTF dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n", zpadlen, spadlen, min, max, place)); #endif /* Spaces */ while (spadlen > 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); --spadlen; } /* Sign */ if (signvalue) total += dopr_outch (buffer, currlen, maxlen, signvalue); /* Zeros */ if (zpadlen > 0) { while (zpadlen > 0) { total += dopr_outch (buffer, currlen, maxlen, '0'); --zpadlen; } } /* Digits */ while (place > 0) total += dopr_outch (buffer, currlen, maxlen, convert[--place]); /* Left Justified spaces */ while (spadlen < 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); ++spadlen; } return total; } static LDOUBLE abs_val (LDOUBLE value) { LDOUBLE result = value; if (value < 0) result = -value; return result; } static LDOUBLE pow10 (int exp) { LDOUBLE result = 1; while (exp) { result *= 10; exp--; } return result; } static long round (LDOUBLE value) { long intpart; intpart = value; value = value - intpart; if (value >= 0.5) intpart++; return intpart; } static int fmtfp (char *buffer, size_t *currlen, size_t maxlen, LDOUBLE fvalue, int min, int max, int flags) { int signvalue = 0; LDOUBLE ufvalue; char iconvert[20]; char fconvert[20]; int iplace = 0; int fplace = 0; int padlen = 0; /* amount to pad */ int zpadlen = 0; int caps = 0; int total = 0; long intpart; long fracpart; /* * AIX manpage says the default is 0, but Solaris says the default * is 6, and sprintf on AIX defaults to 6 */ if (max < 0) max = 6; ufvalue = abs_val (fvalue); if (fvalue < 0) signvalue = '-'; else if (flags & DP_F_PLUS) /* Do a sign (+/i) */ signvalue = '+'; else if (flags & DP_F_SPACE) signvalue = ' '; #if 0 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */ #endif intpart = ufvalue; /* * Sorry, we only support 9 digits past the decimal because of our * conversion method */ if (max > 9) max = 9; /* We "cheat" by converting the fractional part to integer by * multiplying by a factor of 10 */ fracpart = round ((pow10 (max)) * (ufvalue - intpart)); if (fracpart >= pow10 (max)) { intpart++; fracpart -= pow10 (max); } #ifdef DEBUG_SNPRINTF dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart)); #endif /* Convert integer part */ do { iconvert[iplace++] = (caps? "0123456789ABCDEF":"0123456789abcdef")[intpart % 10]; intpart = (intpart / 10); } while(intpart && (iplace < 20)); if (iplace == 20) iplace--; iconvert[iplace] = 0; /* Convert fractional part */ do { fconvert[fplace++] = (caps? "0123456789ABCDEF":"0123456789abcdef")[fracpart % 10]; fracpart = (fracpart / 10); } while(fracpart && (fplace < 20)); if (fplace == 20) fplace--; fconvert[fplace] = 0; /* -1 for decimal point, another -1 if we are printing a sign */ padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0); zpadlen = max - fplace; if (zpadlen < 0) zpadlen = 0; if (padlen < 0) padlen = 0; if (flags & DP_F_MINUS) padlen = -padlen; /* Left Justifty */ if ((flags & DP_F_ZERO) && (padlen > 0)) { if (signvalue) { total += dopr_outch (buffer, currlen, maxlen, signvalue); --padlen; signvalue = 0; } while (padlen > 0) { total += dopr_outch (buffer, currlen, maxlen, '0'); --padlen; } } while (padlen > 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); --padlen; } if (signvalue) total += dopr_outch (buffer, currlen, maxlen, signvalue); while (iplace > 0) total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]); /* * Decimal point. This should probably use locale to find the correct * char to print out. */ if (max > 0) { total += dopr_outch (buffer, currlen, maxlen, '.'); while (fplace > 0) total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]); } while (zpadlen > 0) { total += dopr_outch (buffer, currlen, maxlen, '0'); --zpadlen; } while (padlen < 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); ++padlen; } return total; } static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c) { if (*currlen + 1 < maxlen) buffer[(*currlen)++] = c; return 1; } #ifndef HAVE_VSNPRINTF int vsnprintf (char *str, size_t count, const char *fmt, va_list args) { if (str != NULL) str[0] = 0; return dopr(str, count, fmt, args); } #endif /* !HAVE_VSNPRINTF */ #ifndef HAVE_SNPRINTF /* VARARGS3 */ #ifdef HAVE_STDARGS int snprintf (char *str,size_t count,const char *fmt,...) #else int snprintf (va_alist) va_dcl #endif { #ifndef HAVE_STDARGS char *str; size_t count; char *fmt; #endif VA_LOCAL_DECL; int total; VA_START (fmt); VA_SHIFT (str, char *); VA_SHIFT (count, size_t ); VA_SHIFT (fmt, char *); total = vsnprintf(str, count, fmt, ap); VA_END; return total; } #endif /* !HAVE_SNPRINTF */ #ifdef TEST_SNPRINTF #ifndef LONG_STRING #define LONG_STRING 1024 #endif int main (void) { char buf1[LONG_STRING]; char buf2[LONG_STRING]; char *fp_fmt[] = { "%-1.5f", "%1.5f", "%123.9f", "%10.5f", "% 10.5f", "%+22.9f", "%+4.9f", "%01.3f", "%4f", "%3.1f", "%3.2f", "%.0f", "%.1f", NULL }; double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996, 0.9996, 1.996, 4.136, 0}; char *int_fmt[] = { "%-1.5d", "%1.5d", "%123.9d", "%5.5d", "%10.5d", "% 10.5d", "%+22.33d", "%01.3d", "%4d", NULL }; long int_nums[] = { -1, 134, 91340, 341, 0203, 0}; int x, y; int fail = 0; int num = 0; printf ("Testing snprintf format codes against system sprintf...\n"); for (x = 0; fp_fmt[x] != NULL ; x++) for (y = 0; fp_nums[y] != 0 ; y++) { snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]); sprintf (buf2, fp_fmt[x], fp_nums[y]); if (strcmp (buf1, buf2)) { printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n", fp_fmt[x], buf1, buf2); fail++; } num++; } for (x = 0; int_fmt[x] != NULL ; x++) for (y = 0; int_nums[y] != 0 ; y++) { snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]); sprintf (buf2, int_fmt[x], int_nums[y]); if (strcmp (buf1, buf2)) { printf("snprintf doesn't match Format: %s\n\tsnprintf = %s\n\tsprintf = %s\n", int_fmt[x], buf1, buf2); fail++; } num++; } printf ("%d tests failed out of %d.\n", fail, num); } #endif /* SNPRINTF_TEST */ #endif /* !HAVE_SNPRINTF */ clearsilver-0.10.5/util/test/0000755001211700116100000000000010645505044013043 500000000000000clearsilver-0.10.5/util/test/Makefile0000644001211700116100000000456310455366741014443 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = ../../ endif include $(NEOTONIC_ROOT)rules.mk HDFTEST_EXE = hdftest HDFTEST_SRC = hdftest.c HDFTEST_OBJ = $(HDFTEST_SRC:%.c=%.o) HDFSORTTEST_EXE = hdf_sort_test HDFSORTTEST_SRC = hdf_sort_test.c HDFSORTTEST_OBJ = $(HDFSORTTEST_SRC:%.c=%.o) HDFLOADTEST_EXE = hdfloadtest HDFLOADTEST_SRC = hdfloadtest.c HDFLOADTEST_OBJ = $(HDFLOADTEST_SRC:%.c=%.o) LISTDIRTEST_EXE = listdir_test LISTDIRTEST_SRC = listdir_test.c LISTDIRTEST_OBJ = $(LISTDIRTEST_SRC:%.c=%.o) HDFCOPYTEST_EXE = hdf_copy_test HDFCOPYTEST_SRC = hdf_copy_test.c HDFCOPYTEST_OBJ = $(HDFCOPYTEST_SRC:%.c=%.o) HDFDEALLOCTEST_EXE = hdf_dealloc_test HDFDEALLOCTEST_SRC = hdf_dealloc_test.c HDFDEALLOCTEST_OBJ = $(HDFDEALLOCTEST_SRC:%.c=%.o) NETTEST_EXE = net_test NETTEST_SRC = net_test.c NETTEST_OBJ = $(NETTEST_SRC:%.c=%.o) DATETEST_EXE = date_test DATETEST_SRC = date_test.c DATETEST_OBJ = $(DATETEST_SRC:%.c=%.o) HASHTEST_EXE = hash_test HASHTEST_SRC = hash_test.c HASHTEST_OBJ = $(HASHTEST_SRC:%.c=%.o) ULISTTEST_EXE = ulist_test ULISTTEST_SRC = ulist_test.c ULISTTEST_OBJ = $(ULISTTEST_SRC:%.c=%.o) CFLAGS += -I$(NEOTONIC_ROOT)/util LIBS += -lneo_utl TARGETS = $(HDFTEST_EXE) $(LISTDIRTEST_EXE) $(HDFCOPYTEST_EXE) \ $(HDFSORTTEST_EXE) $(HDFDEALLOCTEST_EXE) \ $(HDFLOADTEST_EXE) $(NETTEST_EXE) $(DATETEST_EXE) \ $(HASHTEST_EXE) $(ULISTTEST_EXE) all: $(TARGETS) $(ULISTTEST_EXE): $(ULISTTEST_OBJ) $(NTR_LIB) $(LD) $@ $(ULISTTEST_OBJ) $(LDFLAGS) $(LIBS) $(HDFTEST_EXE): $(HDFTEST_OBJ) $(NTR_LIB) $(LD) $@ $(HDFTEST_OBJ) $(LDFLAGS) $(LIBS) $(HDFSORTTEST_EXE): $(HDFSORTTEST_OBJ) $(NTR_LIB) $(LD) $@ $(HDFSORTTEST_OBJ) $(LDFLAGS) $(LIBS) $(HDFDEALLOCTEST_EXE): $(HDFDEALLOCTEST_OBJ) $(NTR_LIB) $(LD) $@ $(HDFDEALLOCTEST_OBJ) $(LDFLAGS) $(LIBS) $(HDFLOADTEST_EXE): $(HDFLOADTEST_OBJ) $(NTR_LIB) $(LD) $@ $(HDFLOADTEST_OBJ) $(LDFLAGS) $(LIBS) # -lefence $(LISTDIRTEST_EXE): $(LISTDIRTEST_OBJ) $(NTR_LIB) $(LD) $@ $(LISTDIRTEST_OBJ) $(LDFLAGS) $(LIBS) $(HDFCOPYTEST_EXE): $(HDFCOPYTEST_OBJ) $(NTR_LIB) $(LD) $@ $(HDFCOPYTEST_OBJ) $(LDFLAGS) $(LIBS) # -lefence $(NETTEST_EXE): $(NETTEST_OBJ) $(NTR_LIB) $(LD) $@ $(NETTEST_OBJ) $(LDFLAGS) $(LIBS) $(DATETEST_EXE): $(DATETEST_OBJ) $(NTR_LIB) $(LD) $@ $(DATETEST_OBJ) $(LDFLAGS) $(LIBS) $(HASHTEST_EXE): $(HASHTEST_OBJ) $(NTR_LIB) $(LD) $@ $(HASHTEST_OBJ) $(LDFLAGS) $(LIBS) # -lefence clean: $(RM) *.o distclean: $(RM) $(TARGETS) *.o clearsilver-0.10.5/util/test/date_test.c0000644001211700116100000000235110261037532015100 00000000000000 #include "cs_config.h" #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_date.h" int main(int argc, char *argv[]) { time_t t; struct tm ttm; char buf[256]; fprintf(stderr, "Starting...\n"); fprintf(stderr, "TZ is %s\n", getenv("TZ")); fprintf(stderr, "TZ Offset is %ld\n", timezone); memset(&ttm, 0, sizeof(struct tm)); t = 996887354; fprintf(stderr, "US/Eastern Test\n"); neo_time_expand(t, "US/Eastern", &ttm); fprintf(stderr, "TZ is %s\n", getenv("TZ")); fprintf(stderr, "TZ Offset is %ld\n", timezone); fprintf(stderr, "TZ Offset is %ld\n", neo_tz_offset(&ttm)); fprintf(stderr, "From tm: %s %ld\n", ttm.tm_zone, ttm.tm_gmtoff); strftime(buf, sizeof(buf), "%Y/%m/%d %H:%M:%S", &ttm); fprintf(stderr, "Time is %s\n", buf); fprintf(stderr, "GMT Test\n"); neo_time_expand(t, "GMT", &ttm); fprintf(stderr, "TZ is %s\n", getenv("TZ")); fprintf(stderr, "TZ Offset is %ld\n", timezone); fprintf(stderr, "TZ Offset is %ld\n", neo_tz_offset(&ttm)); fprintf(stderr, "From tm: %s %ld\n", ttm.tm_zone, ttm.tm_gmtoff); strftime(buf, sizeof(buf), "%Y/%m/%d %H:%M:%S", &ttm); fprintf(stderr, "Time is %s\n", buf); return 0; } clearsilver-0.10.5/util/test/hash_test.c0000644001211700116100000000473310261037532015114 00000000000000 #include "cs_config.h" #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_hash.h" void dump_string_hash(NE_HASH *hash) { NE_HASHNODE *node; int x; for (x = 0; x < hash->size; x++) { ne_warn("Node %d", x); for (node = hash->nodes[x]; node; node = node->next) { ne_warn(" %s = %s [%8x | %d]", node->key, node->value, node->hashv, node->hashv & (hash->size - 1)); } } } NEOERR *dictionary_test (void) { NEOERR *err = STATUS_OK; int x; char *word; NE_HASH *hash = NULL; FILE *fp; char buf[256]; err = ne_hash_init(&hash, ne_hash_str_hash, ne_hash_str_comp); if (err) return nerr_pass(err); fp = fopen ("/usr/dict/words", "r"); if (fp == NULL) { fp = fopen ("/usr/share/dict/words", "r"); if (fp == NULL) return nerr_raise_errno(NERR_IO, "Unable to open file /usr/dict/words"); } ne_warn("Loading words into hash"); while (fgets (buf, sizeof(buf), fp) != NULL) { x = strlen (buf); if (buf[x-1] == '\n') buf[x-1] = '\0'; word = strdup(buf); err = ne_hash_insert(hash, word, word); if (err) break; word = ne_hash_lookup(hash, buf); if (word == NULL) { err = nerr_raise(NERR_ASSERT, "Unable to find word %s in hash", buf); break; } if (strcmp(word, buf)) { err = nerr_raise(NERR_ASSERT, "Lookup returned wrong word: %s != %s", buf, word); break; } } fclose (fp); ne_warn("Loaded %d words", hash->num); if (err) { dump_string_hash(hash); return nerr_pass(err); } fp = fopen ("/usr/dict/words", "r"); if (fp == NULL) { fp = fopen ("/usr/share/dict/words", "r"); if (fp == NULL) return nerr_raise_errno(NERR_IO, "Unable to open file /usr/dict/words"); } ne_warn("Testing words in hash"); while (fgets (buf, sizeof(buf), fp) != NULL) { x = strlen (buf); if (buf[x-1] == '\n') buf[x-1] = '\0'; if (!(word = ne_hash_lookup(hash, buf))) { err = nerr_raise(NERR_ASSERT, "Unable to find word %s in hash", buf); break; } if (strcmp(word, buf)) { err = nerr_raise(NERR_ASSERT, "Lookup returned wrong word: %s != %s", buf, word); break; } } fclose (fp); ne_hash_destroy(&hash); return nerr_pass(err); } int main(int argc, char **argv) { NEOERR *err; err = dictionary_test(); if (err) { nerr_log_error(err); printf("FAIL\n"); return -1; } printf("PASS\n"); return 0; } clearsilver-0.10.5/util/test/hdf_copy_test.c0000644001211700116100000000230310467213621015756 00000000000000 #include "cs_config.h" #include #include #include "util/neo_misc.h" #include "util/neo_hdf.h" int main(void) { HDF *hdf_1, *hdf_2; HDF *cur_node,*last_node; hdf_init(&hdf_1); hdf_read_file(hdf_1,"hdf_copy_test.hdf"); hdf_dump(hdf_1,NULL); cur_node = hdf_get_obj(hdf_1,"Chart"); last_node = cur_node; cur_node = hdf_get_obj(cur_node,"next_stage"); while (hdf_get_obj(cur_node,"next_stage") && strcmp(hdf_get_value(cur_node,"Bucket.FieldId",""),"QUEUE")) { last_node = cur_node; cur_node = hdf_get_obj(cur_node,"next_stage"); } if (hdf_get_obj(cur_node,"next_stage")) { hdf_copy(hdf_1,"TempHolderPlace",hdf_get_obj(cur_node,"next_stage")); } ne_warn("Delete tree from node: %s", hdf_obj_name(last_node)); hdf_remove_tree(last_node,"next_stage"); hdf_dump(hdf_1,NULL); fprintf(stderr,"-----------------\n"); hdf_copy(last_node,"next_stage",hdf_get_obj(hdf_1,"TempHolderPlace")); hdf_dump(hdf_1,NULL); /* Test copy and destroy, make sure we actually copy everything and * don't reference anything */ hdf_init(&hdf_2); hdf_copy(hdf_2, "", hdf_1); hdf_destroy(&hdf_1); hdf_dump(hdf_2, NULL); hdf_destroy(&hdf_2); return 0; } clearsilver-0.10.5/util/test/hdf_copy_test.hdf0000644001211700116100000000203210467206007016274 00000000000000 # -------------------------------------------------- # this is an example definition of a chart pipeline # DataSource = outfile.sdb DataSource { # TODO: specify time range for the dataset.... } DomainData { # TODO: include data values for agents, queues, etc. } Filters { # TODO: configure filters to limit data } Chart { next_stage { id [attr=1, batter] = 1 Type = Mux Bucket = Discrete Bucket.FieldId = QUEUE Bucket.Dimension = Y next_stage { id [attr=2, batter] = 2 Type = Mux Bucket = Time Bucket.FieldId = TIME Bucket.Dimension = Y next_stage { id [attr=3] = 3 Type = Mux Bucket = Discrete Bucket.FieldId = AGENT Bucket.Dimension = X next_stage { id = 4 Type = Accumulator } } } } } clearsilver-0.10.5/util/test/hdf_dealloc_test.c0000644001211700116100000000107410261037532016410 00000000000000 #include "cs_config.h" #include #include "util/neo_misc.h" #include "util/neo_hdf.h" #include "util/neo_rand.h" int main(int argc, char *argv[]) { HDF *hdf = NULL; int i, j; hdf_init(&hdf); ne_warn("creating 100000x10 nodes"); for (i = 0; i < 100000; i++) { char buffer[64]; for (j = 0; j < 10; j++) { snprintf(buffer, sizeof(buffer), "node.%d.test.%d", i, j); hdf_set_value(hdf, buffer, "test"); } } ne_warn("calling dealloc"); hdf_destroy(&hdf); // <-- this takes forever to return with a hugely return 0; } clearsilver-0.10.5/util/test/hdf_hash_test.c0000644001211700116100000000120110261037533015721 00000000000000 #include "cs_config.h" #include #include "util/neo_misc.h" #include "util/neo_hdf.h" #include "util/neo_rand.h" int main(int argc, char *argv[]) { NEOERR *err; HDF *hdf, *h2; err = hdf_init(&hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = hdf_set_value(hdf, "CGI.Foo", "Bar"); if (err) { nerr_log_error(err); return -1; } err = hdf_set_value(hdf, "CGI.Foo", "Baz"); if (err) { nerr_log_error(err); return -1; } h2 = hdf_get_obj(hdf, "CGI"); err = hdf_set_value(h2, "Foo", "Bang"); hdf_dump(hdf, NULL); hdf_destroy(&hdf); return 0; } clearsilver-0.10.5/util/test/hdf_sort_test.c0000644001211700116100000000236410261037533016000 00000000000000 #include "cs_config.h" #include #include #include "util/neo_misc.h" #include "util/neo_hdf.h" #include "util/neo_rand.h" int TestCompare(const void* pa, const void* pb) { HDF **a = (HDF **)pa; HDF **b = (HDF **)pb; float aVal,bVal; aVal = atof(hdf_get_value(*a,"val","0")); bVal = atof(hdf_get_value(*b,"val","0")); printf("TestCompare aVal=%f [%s] bVal=%f [%s]\n",aVal,hdf_get_value(*a,"name","?"),bVal,hdf_get_value(*b,"name","?")); if (aVal #include "util/neo_misc.h" #include "util/neo_hdf.h" #include "util/neo_rand.h" #include "util/neo_files.h" int main(int argc, char *argv[]) { NEOERR *err; HDF *hdf; int x; double tstart = 0; double tend = 0; char *file; int reps = 1000; char *s = NULL; if (argc > 1) file = argv[1]; else file = "test.hdf"; if (argc > 2) reps = atoi(argv[2]); err = hdf_init(&hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } tstart = ne_timef(); for (x = 0; x < reps; x++) { err = hdf_read_file(hdf, file); if (err != STATUS_OK) { nerr_log_error(err); return -1; } } tend = ne_timef(); ne_warn("hdf_read_file test finished in %5.3fs, %5.3fs/rep", tend - tstart, (tend-tstart) / reps); tstart = ne_timef(); for (x = 0; x < reps; x++) { err = ne_load_file(file, &s); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = hdf_read_string(hdf, s); if (err != STATUS_OK) { nerr_log_error(err); return -1; } free(s); } tend = ne_timef(); ne_warn("load/hdf_read_string test finished in %5.3fs, %5.3fs/rep", tend - tstart, (tend-tstart) / reps); err = ne_load_file(file, &s); if (err != STATUS_OK) { nerr_log_error(err); return -1; } tstart = ne_timef(); for (x = 0; x < reps; x++) { err = hdf_read_string(hdf, s); if (err != STATUS_OK) { nerr_log_error(err); return -1; } } tend = ne_timef(); free(s); ne_warn("hdf_read_string test finished in %5.3fs, %5.3fs/rep", tend - tstart, (tend-tstart) / reps); /* hdf_dump(hdf, NULL); */ hdf_destroy(&hdf); return 0; } clearsilver-0.10.5/util/test/hdftest.c0000644001211700116100000000702410350133212014556 00000000000000 #include "cs_config.h" #include #include #include "util/neo_misc.h" #include "util/neo_hdf.h" #include "util/neo_rand.h" #define DIE_NOT_OK(err) \ if (err != STATUS_OK) { \ nerr_log_error(err); \ exit(-1); \ } int rand_name (char *s, int slen) { char buf[256]; int x, m, l, rl; m = neo_rand(10); while (1) { neo_rand_word(s, slen); if (!strchr(s, '.')) break; } for (x = 1; x < m; x++) { l = strlen(s); neo_rand_word(buf, sizeof(buf)); rl = strlen(buf); /* fprintf(stderr, "%s\n", buf); */ if (rl && slen - l - rl > 1 && !strchr(buf, '.')) { snprintf(s + l, slen - l, ".%s", buf); } } return 0; } static int sortByName(const void *a, const void *b) { HDF **ha = (HDF **)a; HDF **hb = (HDF **)b; /* fprintf(stderr, "%s <=> %s\n", hdf_obj_name(*ha), hdf_obj_name(*hb)); */ return strcasecmp(hdf_obj_name(*ha), hdf_obj_name(*hb)); } int main(int argc, char *argv[]) { NEOERR *err; HDF *hdf; int x; char name[256]; char value[256]; double tstart = 0; err = hdf_init(&hdf); DIE_NOT_OK(err); err = hdf_set_value (hdf, "Beware", "1"); DIE_NOT_OK(err); err = hdf_set_value (hdf, "Beware.The", "2"); DIE_NOT_OK(err); err = hdf_set_valuef (hdf, "Beware.The.%s=%d", "Ides", 3); DIE_NOT_OK(err); err = hdf_set_value (hdf, "Beware.Off", "4"); DIE_NOT_OK(err); err = hdf_set_value (hdf, "Beware.The.Ides.Of", "5"); DIE_NOT_OK(err); err = hdf_set_value (hdf, "Beware.The.Butter", "6"); DIE_NOT_OK(err); err = hdf_set_attr (hdf, "Beware.The.Butter", "Lang", "en"); DIE_NOT_OK(err); err = hdf_set_attr (hdf, "Beware.The.Butter", "Lang", "1"); DIE_NOT_OK(err); err = hdf_set_attr (hdf, "Beware.The.Butter", "Lang", NULL); DIE_NOT_OK(err); err = hdf_read_file (hdf, "test.hdf"); DIE_NOT_OK(err); hdf_dump(hdf, NULL); x = hdf_get_int_value (hdf, "Beware.The.Ides", 0); if (x != 3) { ne_warn("hdf_get_int_value returned %d, expected 3", x); return -1; } /* test symlinks */ { const char *v; err = hdf_set_value(hdf, "Destination.Foo", "bar"); DIE_NOT_OK(err); err = hdf_set_symlink(hdf, "Symlink.baz", "Destination.Foo"); DIE_NOT_OK(err); v = hdf_get_value(hdf, "Symlink.baz", "notfound"); if (strcmp(v, "bar")) { ne_warn("hdf_get_value through symlink returned %s, expected bar", v); return -1; } err = hdf_set_value(hdf, "Symlink.baz", "newvalue"); DIE_NOT_OK(err); v = hdf_get_value(hdf, "Symlink.baz", "notfound"); if (strcmp(v, "newvalue")) { ne_warn("hdf_get_value through symlink returned %s, expected newvalue", v); return -1; } err = hdf_set_value(hdf, "Symlink.baz.too", "newtoo"); DIE_NOT_OK(err); v = hdf_get_value(hdf, "Symlink.baz.too", "newtoo"); if (strcmp(v, "newtoo")) { ne_warn("hdf_get_value through symlink returned %s, expected newtoo", v); return -1; } v = hdf_get_value(hdf, "Destination.Foo.too", "newtoo"); if (strcmp(v, "newtoo")) { ne_warn("hdf_get_value through symlink returned %s, expected newtoo", v); return -1; } } for (x = 0; x < 10000; x++) { rand_name(name, sizeof(name)); neo_rand_word(value, sizeof(value)); /* ne_warn("Setting %s = %s", name, value); */ err = hdf_set_value (hdf, name, value); DIE_NOT_OK(err); } tstart = ne_timef(); hdf_sort_obj(hdf, sortByName); ne_warn("sort took %5.5fs", ne_timef() - tstart); hdf_dump(hdf, NULL); hdf_destroy(&hdf); return 0; } clearsilver-0.10.5/util/test/listdir_test.c0000644001211700116100000000167610261037533015647 00000000000000 #include "cs_config.h" #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/ulist.h" #include "util/neo_files.h" int main(int argc, char **argv) { char *path; ULIST *files = NULL; char *filename; NEOERR *err; int x; if (argc > 1) path = argv[1]; else path = "."; ne_warn("Testing ne_listdir()"); err = ne_listdir(path, &files); if (err) { nerr_log_error(err); return -1; } for (x = 0; x < uListLength(files); x++) { err = uListGet(files, x, (void *)&filename); printf("%s\n", filename); } uListDestroy(&files, ULIST_FREE); ne_warn("Testing ne_listdir_match() with *.c"); err = ne_listdir_match(path, &files, "*.c"); if (err) { nerr_log_error(err); return -1; } for (x = 0; x < uListLength(files); x++) { err = uListGet(files, x, (void *)&filename); printf("%s\n", filename); } uListDestroy(&files, ULIST_FREE); return 0; } clearsilver-0.10.5/util/test/net_test.c0000644001211700116100000000704710261037533014761 00000000000000 #include "cs_config.h" #include #include #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_net.h" #include "util/ulist.h" #include "util/neo_rand.h" #define TEST_PORT 46032 #define COUNT 10000 typedef struct _rand_thing { int is_num; int n; char *s; } RAND_THING; NEOERR *client_proc(int port, ULIST *stuff) { NEOERR *err; NSOCK *nsock; int x; RAND_THING *thing; sleep(1); ne_warn("[c] Connecting to port %d", port); err = ne_net_connect(&nsock, "localhost", port, 10, 10); if (err) return nerr_pass(err); ne_warn("[c] Connected."); do { err = ne_net_write_int(nsock, uListLength(stuff)); if (err) break; for (x = 0; x < uListLength(stuff); x++) { err = uListGet(stuff, x, (void *)&thing); if (err) break; if (thing->is_num) { err = ne_net_write_int(nsock, thing->n); /* ne_warn("[c] Sending %d", thing->n); */ } else { err = ne_net_write_str(nsock, thing->s); /* ne_warn("[c] Sending %s", thing->s); */ } if (err) break; } } while (0); ne_net_close(&nsock); return nerr_pass(err); } NEOERR *server_proc(int port, ULIST *stuff) { NEOERR *err; int server; NSOCK *nsock; int x, i; RAND_THING *thing; char *s; ne_warn("[s] Listening on port %d", port); err = ne_net_listen(port, &server); if (err) return nerr_pass(err); err = ne_net_accept(&nsock, server, 10); if (err) return nerr_pass(err); ne_warn("[s] Connection."); do { err = ne_net_read_int(nsock, &x); if (err) break; if (x != uListLength(stuff)) { err = nerr_raise(NERR_ASSERT, "Incoming length is not equal to expected length: %d != %d", x, uListLength(stuff)); break; } for (x = 0; x < uListLength(stuff); x++) { err = uListGet(stuff, x, (void *)&thing); if (err) break; if (thing->is_num) { err = ne_net_read_int(nsock, &i); if (err) break; /* ne_warn("[s] Received %d", i); */ if (thing->n != i) { err = nerr_raise(NERR_ASSERT, "Incoming %d number is not equal to expected: %d != %d", x, i, thing->n); break; } } else { err = ne_net_read_str_alloc(nsock, &s, NULL); if (err) break; /* ne_warn("[s] Received %s", s); */ if (strcmp(s, thing->s)) { err = nerr_raise(NERR_ASSERT, "Incoming %d string is not equal to expected: '%s' != '%s'", x, s, thing->s); break; } free(s); } printf("\rs"); } } while (0); ne_net_close(&nsock); return nerr_pass(err); } NEOERR *run_test(void) { NEOERR *err; ULIST *stuff; char word[64000]; RAND_THING *thing; pid_t child; int x; ne_warn("starting net_test"); ne_warn("generating random list"); err = uListInit(&stuff, COUNT, 0); if (err) return nerr_pass(err); for (x = 0; x < COUNT; x++) { thing = (RAND_THING *) calloc(1, sizeof(RAND_THING)); if (neo_rand(100) > 50) { thing->is_num = 1; thing->n = neo_rand(1000000); } else { neo_rand_word(word, sizeof(word)); thing->s = strdup(word); } err = uListAppend(stuff, thing); if (err) return nerr_pass(err); } child = fork(); if (!child) { /* child */ return nerr_pass(client_proc(TEST_PORT, stuff)); } /* parent */ err = server_proc(TEST_PORT, stuff); if (!err) waitpid(child, NULL, 0); return nerr_pass(err); } int main(int argc, char **argv) { NEOERR *err; nerr_init(); err = run_test(); if (err) { nerr_log_error(err); return -1; } return 0; } clearsilver-0.10.5/util/test/test.hdf0000644001211700116100000000071610261037533014426 00000000000000#This is a test # file for our hdf loader Test.Wow = Foo Test.Foo : Test.Wow Test.Embedded { Foo = Bar Bar { Baz [Lang] = Boom } Bar [Lang=en] = Barn bar [tag="help me"]= Door Bar2 { Born = Again } Attr1 [tag="baseball",fielder=catcher,basehit] = 1 Attr2 [tag="baseball", fielder=catcher,basehit] = 1 Attr3 [tag="baseball",fielder=catcher, basehit] = 1 Attr4 [tag="baseball", fielder=catcher, basehit] = 1 } #include "test2.hdf" clearsilver-0.10.5/util/test/test2.hdf0000644001211700116100000000012710261037533014504 00000000000000 Multiline.Test << EOB This is a test of the multiline setting code.... Wow! EOB clearsilver-0.10.5/util/test/ulist_test.c0000644001211700116100000000214510261037533015325 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * Tests for ulist library */ #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/ulist.h" NEOERR *TestIntegerStorage() { NEOERR *err; ULIST *arr; int x; // Simple append test err = uListInit(&arr, 100, 0); if (err) return nerr_pass(err); for (x = 0; x < 1000; x++) { err = uListAppend(arr, (void *)x); if (err) return nerr_pass(err); } for (x = 0; x < 1000; x++) { int y; err = uListGet(arr, x, (void *)&y); if (err) return nerr_pass(err); if (x != y) { return nerr_raise(NERR_ASSERT, "Value returned didn't match value stored: Got %d, Expected %d", y, x); } } return STATUS_OK; } int main(int argc, char *argv[]) { NEOERR *err; nerr_init(); err = TestIntegerStorage(); if (err) { nerr_log_error(err); printf("FAIL\n"); return -1; } printf("PASS\n"); return 0; } clearsilver-0.10.5/util/ulist.c0000644001211700116100000001217010261037533013306 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "ulist.h" #define ULIST_DEFAULT_SIZE 10 static NEOERR *check_resize (ULIST *ul, int size) { if (size > ul->max) { void **new_items; int new_size = 0; new_size = ul->max*2; if (size > new_size) { new_size = size + ul->max; } new_items = (void **) realloc ((void *)(ul->items), new_size * sizeof(void *)); if (new_items == NULL) { return nerr_raise(NERR_NOMEM, "Unable to resize ULIST to %d: Out of memory", new_size); } ul->items = new_items; ul->max = new_size; } return STATUS_OK; } NEOERR *uListInit(ULIST **ul, int size, int flags) { ULIST *r_ul; *ul = NULL; if (size == 0) { size = ULIST_DEFAULT_SIZE; } r_ul = (ULIST *) calloc (1, sizeof (ULIST)); if (r_ul == NULL) { return nerr_raise(NERR_NOMEM, "Unable to create ULIST: Out of memory"); } r_ul->items = (void **) calloc (size, sizeof(void *)); if (r_ul->items == NULL) { free (r_ul); return nerr_raise(NERR_NOMEM, "Unable to create ULIST: Out of memory"); } r_ul->num = 0; r_ul->max = size; r_ul->flags = flags; *ul = r_ul; return STATUS_OK; } NEOERR *uListvInit(ULIST **ul, ...) { NEOERR *err; va_list ap; void *it; err = uListInit (ul, 0, 0); if (err) return nerr_pass (err); va_start (ap, ul); it = va_arg (ap, void *); while (it) { err = uListAppend (*ul, it); if (err) { uListDestroy(ul, 0); return nerr_pass (err); } it = va_arg (ap, void *); } return STATUS_OK; } NEOERR *uListAppend (ULIST *ul, void *data) { NEOERR *r; r = check_resize (ul, ul->num + 1); if (r != STATUS_OK) return r; ul->items[ul->num] = data; ul->num++; return STATUS_OK; } NEOERR *uListPop (ULIST *ul, void **data) { if (ul->num == 0) return nerr_raise(NERR_OUTOFRANGE, "uListPop: empty list"); *data = ul->items[ul->num - 1]; ul->num--; return STATUS_OK; } NEOERR *uListInsert (ULIST *ul, int x, void *data) { void **start; NEOERR *r; if (x < 0) x = ul->num + x; if (x >= ul->num) return nerr_raise(NERR_OUTOFRANGE, "uListInsert: past end (%d > %d)", x, ul->num); r = check_resize (ul, ul->num + 1); if (r != STATUS_OK) return r; start = &(ul->items[x]); memmove (start + 1, start, (ul->num - x) * sizeof(void *)); ul->items[x] = data; ++ul->num; return STATUS_OK; } NEOERR *uListDelete (ULIST *ul, int x, void **data) { void **start; if (x < 0) x = ul->num + x; if (x >= ul->num) return nerr_raise(NERR_OUTOFRANGE, "uListDelete: past end (%d > %d)", x, ul->num); if (data != NULL) *data = ul->items[x]; start = &(ul->items[x]); memmove (start, start+1, (ul->num - x - 1) * sizeof(void *)); --ul->num; return STATUS_OK; } NEOERR *uListGet (ULIST *ul, int x, void **data) { if (x < 0) x = ul->num + x; if (x >= ul->num) return nerr_raise(NERR_OUTOFRANGE, "uListGet: past end (%d > %d)", x, ul->num); if (x < 0) return nerr_raise(NERR_OUTOFRANGE, "uListGet: past beginning (%d < 0)", x); *data = ul->items[x]; return STATUS_OK; } NEOERR *uListSet (ULIST *ul, int x, void *data) { if (x >= ul->num) return nerr_raise(NERR_OUTOFRANGE, "uListSet: past end (%d > %d)", x, ul->num); ul->items[x] = data; return STATUS_OK; } NEOERR *uListReverse (ULIST *ul) { int i; for (i = 0; i < ul->num/2; ++i) { void *tmp = ul->items[i]; ul->items[i] = ul->items[ul->num-1-i]; ul->items[ul->num-1-i] = tmp; } return STATUS_OK; } NEOERR *uListSort (ULIST *ul, int (*compareFunc)(const void *, const void*)) { qsort(ul->items, ul->num, sizeof(void *), compareFunc); return STATUS_OK; } void *uListSearch (ULIST *ul, const void *key, int (*compareFunc)(const void *, const void*)) { return bsearch(key, ul->items, ul->num, sizeof(void *), compareFunc); } void *uListIn (ULIST *ul, const void *key, int (*compareFunc)(const void *, const void*)) { int i; for (i = 0; i < ul->num; ++i) { if (!compareFunc(key, &ul->items[i])) { return &ul->items[i]; } } return NULL; } int uListIndex (ULIST *ul, const void *key, int (*compareFunc)(const void *, const void*)) { void **p = uListIn(ul, key, compareFunc); return p ? (p - ul->items) : -1; } NEOERR *uListDestroy (ULIST **ul, int flags) { if (flags & ULIST_FREE) { return uListDestroyFunc(ul, free); } else { return uListDestroyFunc(ul, NULL); } } NEOERR *uListDestroyFunc (ULIST **ul, void (*destroyFunc)(void *)) { ULIST *r_ul; r_ul = *ul; if (r_ul == NULL) return STATUS_OK; if (destroyFunc != NULL) { int x; for (x = 0; x < r_ul->num; x++) { (*destroyFunc)(r_ul->items[x]); } } free (r_ul->items); free (r_ul); *ul = NULL; return STATUS_OK; } int uListLength (ULIST *ul) { if (ul == NULL) return 0; return ul->num; } clearsilver-0.10.5/util/ulist.h0000644001211700116100000000261210261037533013313 00000000000000/* * Neotonic ClearSilver Templating System * * This code is made available under the terms of the * Neotonic ClearSilver License. * http://www.neotonic.com/clearsilver/license.hdf * * Copyright (C) 2001 by Brandon Long */ #ifndef __ULIST_H_ #define __ULIST_H_ 1 #include "util/neo_err.h" typedef struct _ulist { int flags; void **items; int num; int max; } ULIST; #define ULIST_INTEGER (1<<0) #define ULIST_FREE (1<<1) #define ULIST_COPY (1<<2) NEOERR * uListInit(ULIST **ul, int size, int flags); NEOERR * uListvInit(ULIST **ul, ...); int uListLength (ULIST *ul); NEOERR * uListAppend (ULIST *ul, void *data); NEOERR * uListPop (ULIST *ul, void **data); NEOERR * uListInsert (ULIST *ul, int x, void *data); NEOERR * uListDelete (ULIST *ul, int x, void **data); NEOERR * uListGet (ULIST *ul, int x, void **data); NEOERR * uListSet (ULIST *ul, int x, void *data); NEOERR * uListReverse (ULIST *ul); NEOERR * uListSort (ULIST *ul, int (*compareFunc)(const void*, const void*)); void *uListSearch (ULIST *ul, const void *key, int (*compareFunc)(const void *, const void*)); void *uListIn (ULIST *ul, const void *key, int (*compareFunc)(const void *, const void*)); int uListIndex (ULIST *ul, const void *key, int (*compareFunc)(const void *, const void*)); NEOERR * uListDestroy (ULIST **ul, int flags); NEOERR * uListDestroyFunc (ULIST **ul, void (*destroyFunc)(void *)); #endif /* __ULIST_H_ */ clearsilver-0.10.5/util/ulocks.c0000644001211700116100000000707610261042507013454 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "neo_files.h" #include "ulocks.h" NEOERR *fCreate(int *plock, const char *file) { NEOERR *err; int lock; char *p; *plock = -1; /* note the default mode of 666 is possibly a security hole in that * someone else can grab your lock and DoS you. For internal use, who * cares? */ if((lock = open(file, O_WRONLY|O_NDELAY|O_APPEND|O_CREAT|O_EXCL, 0666)) < 0) { if (errno == ENOENT) { p = strrchr (file, '/'); if (p != NULL) { *p = '\0'; err = ne_mkdirs(file, 0777); *p = '/'; if (err != STATUS_OK) return nerr_pass(err); lock = open(file, O_WRONLY|O_NDELAY|O_APPEND|O_CREAT, 0666); } } if (errno == EEXIST) return nerr_pass(fFind(plock, file)); if (lock < 0) return nerr_raise_errno (NERR_IO, "Unable to open lock file %s", file); } *plock = lock; return STATUS_OK; } void fDestroy(int lock) { if(lock < 0) return; close(lock); return; } NEOERR *fFind(int *plock, const char *file) { int lock; *plock = -1; if((lock = open(file, O_WRONLY|O_NDELAY|O_APPEND, 0666)) < 0) { if (errno == ENOENT) return nerr_raise (NERR_NOT_FOUND, "Unable to find lock file %s", file); return nerr_raise_errno (NERR_IO, "Unable to open lock file %s", file); } *plock = lock; return STATUS_OK; } NEOERR *fLock(int lock) { if(lockf(lock, F_LOCK, 0) < 0) return nerr_raise_errno (NERR_LOCK, "File lock failed"); return STATUS_OK; } void fUnlock(int lock) { if(lock < 0) return; lockf(lock, F_ULOCK, 0); return; } #ifdef HAVE_PTHREADS NEOERR *mCreate(pthread_mutex_t *mutex) { int err; if((err = pthread_mutex_init(mutex, NULL))) { return nerr_raise (NERR_LOCK, "Unable to initialize mutex: %s", strerror(err)); } return STATUS_OK; } void mDestroy(pthread_mutex_t *mutex) { pthread_mutex_destroy(mutex); return; } NEOERR *mLock(pthread_mutex_t *mutex) { int err; if((err = pthread_mutex_lock(mutex))) return nerr_raise(NERR_LOCK, "Mutex lock failed: %s", strerror(err)); return STATUS_OK; } NEOERR *mUnlock(pthread_mutex_t *mutex) { int err; if((err = pthread_mutex_unlock(mutex))) return nerr_raise(NERR_LOCK, "Mutex unlock failed: %s", strerror(err)); return STATUS_OK; } NEOERR *cCreate(pthread_cond_t *cond) { int err; if((err = pthread_cond_init(cond, NULL))) { return nerr_raise(NERR_LOCK, "Unable to initialize condition variable: %s", strerror(err)); } return STATUS_OK; } void cDestroy(pthread_cond_t *cond) { pthread_cond_destroy(cond); return; } NEOERR *cWait(pthread_cond_t *cond, pthread_mutex_t *mutex) { int err; if((err = pthread_cond_wait(cond, mutex))) return nerr_raise(NERR_LOCK, "Condition wait failed: %s", strerror(err)); return STATUS_OK; } NEOERR *cBroadcast(pthread_cond_t *cond) { int err; if((err = pthread_cond_broadcast(cond))) return nerr_raise(NERR_LOCK, "Condition broadcast failed: %s", strerror(err)); return STATUS_OK; } NEOERR *cSignal(pthread_cond_t *cond) { int err; if((err = pthread_cond_signal(cond))) return nerr_raise (NERR_LOCK, "Condition signal failed: %s", strerror(err)); return STATUS_OK; } #endif clearsilver-0.10.5/util/ulocks.h0000644001211700116100000001326310261042514013452 00000000000000/* * * Thread-safe Skiplist Using Integer Identifiers * Copyright 1998-2000 Scott Shambarger (scott@shambarger.net) * * This software is open source. Permission to use, copy, modify, and * distribute this software for any purpose and without fee is hereby granted, * provided that the above copyright notice appear in all copies. No * warranty of any kind is expressed or implied. Use at your own risk. * * 1/14/2001 blong * Made it use neo errs... probably need to check locking functions * for error returns... * */ #ifndef __ULOCKS_H_ #define __ULOCKS_H_ NEOERR *fCreate(int *plock, const char *file); /* * Function: fCreate - create a file lock. * Description: Creates a file lock on named file . The lock is * returned in . * Input: plock - place for lock. * file - path of file to use as lock. * Output: plock - set to lock identifier. * Return: STATUS_OK on success * NERR_IO on failure * MT-Level: Safe. */ NEOERR *fFind(int *plock, const char *file); /* * Function: fFind - find a file lock. * Description: Find a file identified by the path , and returns a * lock identifier for it in . If the file doesn't * exist, returns true. * Input: plock - place for lock. * file - path of file to use as lock. * Output: plock - set to lock identifier. * Return: STATUS_OK if found * NERR_IO on failure * MT-Level: Safe. */ void fDestroy(int lock); /* * Function: fDestroy - destroy a lock. * Description: Destroys the lock that was created by fCreate() * or fFind(). * Input: lock - Lock to destroy. * Output: None. * Return: None. * MT-Level: Safe for unique . */ NEOERR *fLock(int lock); /* * Function: fLock - acquire file lock. * Description: Acquires the lock identified by . This call * blocks until the lock is acquired. * Input: lock - Lock to acquire. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe. */ void fUnlock(int lock); /* * Function: fUnlock - release file lock. * Description: Releases the lock identified by . * Input: lock - Lock to release. * Output: None. * Return: None. * MT-Level: Safe. */ #ifdef HAVE_PTHREADS #include NEOERR *mCreate(pthread_mutex_t *mutex); /* * Function: mCreate - initialize a mutex. * Description: Initializes the mutex . * Input: mutex - mutex to initialize. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe for unique . */ void mDestroy(pthread_mutex_t *mutex); /* * Function: mDestroy - destroy a mutex. * Description: Destroys the mutex that was initialized by mCreate(). * Input: mutex - mutex to destroy. * Output: None. * Return: None. * MT-Level: Safe for unique . */ NEOERR *mLock(pthread_mutex_t *mutex); /* * Function: mLock - lock a mutex. * Description: Locks the mutex . This call blocks until the mutex * is acquired. * Input: mutex - mutex to lock. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe. */ NEOERR *mUnlock(pthread_mutex_t *mutex); /* * Function: mUnlock - unlock a mutex. * Description: Unlocks the mutex . * Input: mutex - mutex to unlock. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe. */ NEOERR *cCreate(pthread_cond_t *cond); /* * Function: cCreate - initialize a condition variable. * Description: Initializes the condition variable . * Input: cond - condition variable to initialize. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe for unique . */ void cDestroy(pthread_cond_t *cond); /* * Function: cDestroy - destroy a condition variable. * Description: Destroys the condition variable that was * initialized by cCreate(). * Input: cond - condition variable to destroy. * Output: None. * Return: None. * MT-Level: Safe for unique . */ NEOERR *cWait(pthread_cond_t *cond, pthread_mutex_t *mutex); /* * Function: cWait - wait a condition variable signal. * Description: Waits for a signal on condition variable . * The mutex must be locked by the thread. * Input: cond - condition variable to wait on. * mutex - locked mutex to protect . * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe. */ NEOERR *cBroadcast(pthread_cond_t *cond); /* * Function: cBroadcast - broadcast signal to all waiting threads. * Description: Broadcasts a signal to all threads waiting on condition * variable . * Input: cond - condition variable to broadcast on. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe. */ NEOERR *cSignal(pthread_cond_t *cond); /* * Function: cSignal - send signal to one waiting thread. * Description: Sends a signal to one thread waiting on condition * variable . * Input: cond - condition variable to send signal on. * Output: None. * Return: STATUS_OK on success * NERR_LOCK on failure * MT-Level: Safe. */ #endif /* HAVE_PTHREAD */ #endif /* __ULOCKS_H_ */ clearsilver-0.10.5/util/wdb.c0000644001211700116100000010517510261111435012724 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * The wdb is a wrapper around the sleepycat db library which adds * a relatively simple data/column definition. In many respects, this * code is way more complicated than it ever needed to be, but it works, * so I'm loathe to "fix" it. * * One of they key features of this is the ability to update the * "schema" of the wdb without changing all of the existing rows of * data. */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include "neo_misc.h" #include "neo_err.h" #include "dict.h" #include "ulist.h" #include "skiplist.h" #include "wdb.h" #define DEFN_VERSION_1 "WDB-VERSION-200006301" #define PACK_VERSION_1 1 static void string_rstrip (char *s) { size_t len; len = strlen(s); len--; while (len > 0 && isspace(s[len])) { s[len] = '\0'; len--; } return; } static int to_hex (unsigned char ch, unsigned char *s) { unsigned int uvalue = ch; s[1] = "0123456789ABCDEF"[uvalue % 16]; uvalue = (uvalue / 16); s[0] = "0123456789ABCDEF"[uvalue % 16]; return 0; } int Index_hex[128] = { -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1, -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1 }; #define hexval(c) Index_hex[(unsigned int)(c)] /* Encoding means any non-printable characters and : and % */ static NEOERR *wdb_encode_str_alloc (const char *s, char **o) { int x = 0; int c = 0; char *out; unsigned char ch; while (s[x]) { ch = (unsigned char) s[x]; if ((ch < 32) || (ch > 127) || (ch == ':') || (ch == '%') || isspace(ch)) c++; x++; } out = (char *) malloc (sizeof (char) * (x + c * 3) + 1); if (out == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for encoding %s", s); x = 0; c = 0; *o = out; while (s[x]) { ch = (unsigned char) s[x]; if ((ch < 32) || (ch > 127) || (ch == ':') || (ch == '%') || isspace(ch)) { out[c++] = '%'; to_hex (s[x], &out[c]); c+=2; } else { out[c++] = s[x]; } x++; } out[c] = '\0'; return STATUS_OK; } static NEOERR *wdb_decode_str_alloc (const char *s, char **o) { int x = 0; int c = 0; char *out; unsigned char ch; x = strlen(s); /* Overkill, the decoded string will be smaller */ out = (char *) malloc (sizeof (char) * (x + 1)); if (out == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for decoding %s", s); x = 0; c = 0; while (s[x]) { if (s[x] == '%') { x++; ch = hexval(s[x]) << 4; x++; ch |= hexval(s[x]); out[c++] = ch; } else { out[c++] = s[x]; } x++; } out[c] = '\0'; *o = out; return STATUS_OK; } static void free_cb (void *value, void *rock) { free (value); } static void free_col_cb (void *value, void *rock) { WDBColumn *col; col = (WDBColumn *)value; free (col->name); free (col); } static NEOERR *wdb_alloc (WDB **wdb, int flags) { WDB *my_wdb; NEOERR *err = STATUS_OK; my_wdb = (WDB *) calloc (1, sizeof (WDB)); if (my_wdb == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for WDB"); do { err = dictCreate (&(my_wdb->attrs), 0, 2, 5, 0, 0, free_cb, NULL); if (err != STATUS_OK) break; err = dictCreate (&(my_wdb->cols), 0, 2, 5, 0, 0, free_col_cb, NULL); if (err != STATUS_OK) break; err = uListInit (&(my_wdb->cols_l), 0, 0); if (err != STATUS_OK) break; err = skipNewList(&(my_wdb->ondisk), 0, 4, 2, 0, NULL, NULL); if (err != STATUS_OK) break; *wdb = my_wdb; return STATUS_OK; } while (0); wdb_destroy(&my_wdb); return nerr_pass (err); } #define STATE_REQUIRED 1 #define STATE_ATTRIBUTES 2 #define STATE_COLUMN_DEF 3 static NEOERR *wdb_load_defn_v1 (WDB *wdb, FILE *fp) { char line[1024]; int state = 1; char *k, *v; NEOERR *err = STATUS_OK; int colindex = 1; WDBColumn *col; while (fgets(line, sizeof(line), fp) != NULL) { string_rstrip(line); switch (state) { case STATE_REQUIRED: if (!strcmp(line, "attributes")) state = STATE_ATTRIBUTES; else if (!strcmp(line, "columns")) state = STATE_COLUMN_DEF; else { k = line; v = strchr(line, ':'); /* HACK */ if (!strcmp(k, "name") && ((v == NULL) || (v[1] == '\0'))) { v = "dNone"; } else { if (v == NULL) return nerr_raise (NERR_PARSE, "Error parsing %s", line); if (v[1] == '\0') return nerr_raise (NERR_PARSE, "Error parsing %s", line); } v[0] = '\0'; v++; if (!strcmp(k, "key")) { err = wdb_decode_str_alloc (v, &(wdb->key)); if (err) return nerr_pass(err); } else if (!strcmp(k, "name")) { err = wdb_decode_str_alloc (v, &(wdb->name)); if (err) return nerr_pass(err); } else if (!strcmp(k, "ondisk")) { wdb->last_ondisk = atoi (v); } } break; case STATE_ATTRIBUTES: if (!strcmp(line, "columns")) state = STATE_COLUMN_DEF; else { k = line; v = strchr(line, ':'); if (v == NULL) return nerr_raise (NERR_PARSE, "Error parsing %s", line); v[0] = '\0'; v++; err = wdb_decode_str_alloc (k, &k); if (err) return nerr_pass(err); err = wdb_decode_str_alloc (v, &v); if (err) return nerr_pass(err); err = dictSetValue(wdb->attrs, k, v); free(k); if (err) return nerr_pass_ctx(err, "Error parsing %s", line); } break; case STATE_COLUMN_DEF: k = line; v = strchr(line, ':'); if (v == NULL) return nerr_raise (NERR_PARSE, "Error parsing %s", line); if (v[1] == '\0') return nerr_raise (NERR_PARSE, "Error parsing %s", line); v[0] = '\0'; v++; err = wdb_decode_str_alloc (k, &k); if (err) return nerr_pass(err); col = (WDBColumn *) calloc (1, sizeof (WDBColumn)); col->name = k; col->inmem_index = colindex++; col->type = *v; v+=2; col->ondisk_index = atoi(v); err = dictSetValue(wdb->cols, k, col); if (err) return nerr_raise (NERR_PARSE, "Error parsing %s", line); err = uListAppend(wdb->cols_l, col); if (err) return nerr_pass(err); /* stupid skiplist will assert */ if (col->ondisk_index == 0) { return nerr_raise (NERR_ASSERT, "Invalid ondisk mapping for %s", k); } err = skipInsert (wdb->ondisk, col->ondisk_index, (void *)(col->inmem_index), 0); if (err) return nerr_pass_ctx(err, "Unable to update ondisk mapping for %s", k); break; default: return nerr_raise (NERR_ASSERT, "Invalid state %d", state); } } return STATUS_OK; } static NEOERR *wdb_save_defn_v1 (WDB *wdb, FILE *fp) { NEOERR *err = STATUS_OK; WDBColumn *col; char *s = NULL; char *key = NULL; int r, x, len; char *k = NULL; char *v = NULL; /* Write version string */ r = fprintf (fp, "%s\n", DEFN_VERSION_1); if (!r) goto save_err; err = wdb_encode_str_alloc (wdb->name, &s); if (err) goto save_err; r = fprintf (fp, "name:%s\n", s); if (!r) goto save_err; free (s); err = wdb_encode_str_alloc (wdb->key, &s); if (err != STATUS_OK) goto save_err; r = fprintf (fp, "key:%s\n", s); if (!r) goto save_err; free (s); s = NULL; r = fprintf (fp, "ondisk:%d\n", wdb->last_ondisk); if (!r) goto save_err; r = fprintf (fp, "attributes\n"); if (!r) goto save_err; key = NULL; s = (char *) dictNext (wdb->attrs, &key, NULL); while (s) { err = wdb_encode_str_alloc (key, &k); if (err != STATUS_OK) goto save_err; err = wdb_encode_str_alloc (s, &v); if (err != STATUS_OK) goto save_err; r = fprintf (fp, "%s:%s\n", k, v); if (!r) goto save_err; free (k); free (v); k = NULL; v = NULL; s = (char *) dictNext (wdb->attrs, &key, NULL); } s = NULL; r = fprintf (fp, "columns\n"); if (!r) goto save_err; len = uListLength(wdb->cols_l); for (x = 0; x < len; x++) { err = uListGet (wdb->cols_l, x, (void *)&col); if (err) goto save_err; err = wdb_encode_str_alloc (col->name, &s); if (err != STATUS_OK) goto save_err; r = fprintf (fp, "%s:%c:%d\n", s, col->type, col->ondisk_index); if (!r) goto save_err; free(s); s = NULL; } return STATUS_OK; save_err: if (s != NULL) free (s); if (k != NULL) free (k); if (v != NULL) free (v); if (err == STATUS_OK) return nerr_pass(err); return nerr_raise (r, "Unable to save defn"); } static NEOERR *wdb_load_defn (WDB *wdb, const char *name) { char path[_POSIX_PATH_MAX]; char line[1024]; FILE *fp; NEOERR *err = STATUS_OK; snprintf (path, sizeof(path), "%s.wdf", name); fp = fopen (path, "r"); if (fp == NULL) { if (errno == ENOENT) return nerr_raise (NERR_NOT_FOUND, "Unable to open defn %s", name); return nerr_raise_errno (NERR_IO, "Unable to open defn %s", name); } /* Read Version string */ if (fgets (line, sizeof(line), fp) == NULL) { fclose(fp); return nerr_raise_errno (NERR_IO, "Unable to read defn %s", name); } string_rstrip(line); if (!strcmp(line, DEFN_VERSION_1)) { err = wdb_load_defn_v1(wdb, fp); fclose(fp); if (err) return nerr_pass(err); } else { fclose(fp); return nerr_raise (NERR_ASSERT, "Unknown defn version %s: %s", line, name); } wdb->table_version = rand(); return STATUS_OK; } static NEOERR *wdb_save_defn (WDB *wdb, const char *name) { char path[_POSIX_PATH_MAX]; char path2[_POSIX_PATH_MAX]; FILE *fp; NEOERR *err = STATUS_OK; int r; snprintf (path, sizeof(path), "%s.wdf.new", name); snprintf (path2, sizeof(path2), "%s.wdf", name); fp = fopen (path, "w"); if (fp == NULL) return nerr_raise_errno (NERR_IO, "Unable to open defn %s", name); err = wdb_save_defn_v1 (wdb, fp); fclose (fp); if (err != STATUS_OK) { unlink (path); return nerr_pass (err); } r = unlink (path2); if (r == -1 && errno != ENOENT) return nerr_raise_errno (NERR_IO, "Unable to unlink %s", path2); r = link (path, path2); if (r == -1) return nerr_raise_errno (NERR_IO, "Unable to link %s to %s", path, path2); r = unlink (path); wdb->defn_dirty = 0; wdb->table_version = rand(); return STATUS_OK; } NEOERR *wdb_open (WDB **wdb, const char *name, int flags) { WDB *my_wdb; char path[_POSIX_PATH_MAX]; NEOERR *err = STATUS_OK; int r; *wdb = NULL; err = wdb_alloc (&my_wdb, flags); if (err) return nerr_pass(err); my_wdb->path = strdup (name); if (err) { wdb_destroy (&my_wdb); return nerr_pass(err); } err = wdb_load_defn (my_wdb, name); if (err) { wdb_destroy (&my_wdb); return nerr_pass(err); } snprintf (path, sizeof(path), "%s.wdb", name); r = db_open(path, DB_BTREE, 0, 0, NULL, NULL, &(my_wdb->db)); if (r) { wdb_destroy (&my_wdb); return nerr_raise (NERR_DB, "Unable to open database %s: %d", name, r); } *wdb = my_wdb; return STATUS_OK; } NEOERR *wdb_save (WDB *wdb) { if (wdb->defn_dirty) { wdb_save_defn (wdb, wdb->path); } return STATUS_OK; } void wdb_destroy (WDB **wdb) { WDB *my_wdb; my_wdb = *wdb; if (my_wdb == NULL) return; if (my_wdb->defn_dirty) { wdb_save_defn (my_wdb, my_wdb->path); } if (my_wdb->attrs != NULL) { dictDestroy (my_wdb->attrs); } if (my_wdb->cols != NULL) { dictDestroy (my_wdb->cols); } if (my_wdb->cols_l != NULL) { uListDestroy(&(my_wdb->cols_l), 0); } if (my_wdb->ondisk != NULL) { skipFreeList(my_wdb->ondisk); } if (my_wdb->db != NULL) { my_wdb->db->close (my_wdb->db, 0); my_wdb->db = NULL; } if (my_wdb->path != NULL) { free(my_wdb->path); my_wdb->path = NULL; } if (my_wdb->name != NULL) { free(my_wdb->name); my_wdb->name = NULL; } if (my_wdb->key != NULL) { free(my_wdb->key); my_wdb->key = NULL; } free (my_wdb); *wdb = NULL; return; } #define PACK_UB4(pdata, plen, pmax, pn) \ { \ if (plen + 4 > pmax) \ { \ pmax *= 2; \ pdata = realloc ((void *)pdata, pmax); \ if (pdata == NULL) goto pack_err; \ } \ pdata[plen++] = (0x0ff & (pn >> 0)); \ pdata[plen++] = (0x0ff & (pn >> 8)); \ pdata[plen++] = (0x0ff & (pn >> 16)); \ pdata[plen++] = (0x0ff & (pn >> 24)); \ } #define UNPACK_UB4(pdata, plen, pn, pd) \ { \ if (pn + 4 > plen) \ goto pack_err; \ pd = ((0x0ff & pdata[pn+0])<<0) | ((0x0ff & pdata[pn+1])<<8) | \ ((0x0ff & pdata[pn+2])<<16) | ((0x0ff & pdata[pn+3])<<24); \ pn+=4; \ } #define PACK_BYTE(pdata, plen, pmax, pn) \ { \ if (plen + 1 > pmax) \ { \ pmax *= 2; \ pdata = realloc ((void *)pdata, pmax); \ if (pdata == NULL) goto pack_err; \ } \ pdata[plen++] = (0x0ff & (pn >> 0)); \ } #define UNPACK_BYTE(pdata, plen, pn, pd) \ { \ if (pn + 1 > plen) \ goto pack_err; \ pd = pdata[pn++]; \ } #define PACK_STRING(pdata, plen, pmax, dl, ds) \ { \ if (plen + 4 + dl > pmax) \ { \ while (plen + 4 + dl > pmax) \ pmax *= 2; \ pdata = realloc ((void *)pdata, pmax); \ if (pdata == NULL) goto pack_err; \ } \ pdata[plen++] = (0x0ff & (dl >> 0)); \ pdata[plen++] = (0x0ff & (dl >> 8)); \ pdata[plen++] = (0x0ff & (dl >> 16)); \ pdata[plen++] = (0x0ff & (dl >> 24)); \ memcpy (&pdata[plen], ds, dl); \ plen+=dl;\ } #define UNPACK_STRING(pdata, plen, pn, ps) \ { \ int pl; \ if (pn + 4 > plen) \ goto pack_err; \ pl = ((0x0ff & pdata[pn+0])<<0) | ((0x0ff & pdata[pn+1])<<8) | \ ((0x0ff & pdata[pn+2])<<16) | ((0x0ff & pdata[pn+3])<<24); \ pn+=4; \ if (pl) \ { \ ps = (char *)malloc(sizeof(char)*(pl+1)); \ if (ps == NULL) \ goto pack_err; \ memcpy (ps, &pdata[pn], pl); \ ps[pl] = '\0'; \ pn += pl; \ } else { \ ps = NULL; \ } \ } /* A VERSION_1 Row consists of the following data: * UB4 VERSION * UB4 DATA COUNT * DATA where * UB4 ONDISK INDEX * UB1 TYPE * if INT, then UB4 * if STR, then UB4 length and length UB1s */ static NEOERR *pack_row (WDB *wdb, WDBRow *row, void **rdata, int *rdlen) { char *data; int x, len, dlen, dmax; char *s; int n; WDBColumn *col; NEOERR *err; *rdata = NULL; *rdlen = 0; /* allocate */ data = (char *)malloc(sizeof (char) * 1024); if (data == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to pack row"); dmax = 1024; dlen = 0; PACK_UB4 (data, dlen, dmax, PACK_VERSION_1); /* PACK_UB4 (data, dlen, dmax, time(NULL)); */ len = uListLength(wdb->cols_l); if (len > row->data_count) len = row->data_count; PACK_UB4 (data, dlen, dmax, len); for (x = 0; x < len; x++) { err = uListGet (wdb->cols_l, x, (void *)&col); if (err) goto pack_err; PACK_UB4 (data, dlen, dmax, col->ondisk_index); PACK_BYTE (data, dlen, dmax, col->type); switch (col->type) { case WDB_TYPE_INT: n = (int)(row->data[x]); PACK_UB4 (data, dlen, dmax, n); break; case WDB_TYPE_STR: s = (char *)(row->data[x]); if (s == NULL) { s = ""; } n = strlen(s); PACK_STRING (data, dlen, dmax, n, s); break; default: free (data); return nerr_raise (NERR_ASSERT, "Unknown type %d", col->type); } } *rdata = data; *rdlen = dlen; return STATUS_OK; pack_err: if (data != NULL) free (data); if (err == STATUS_OK) return nerr_raise(NERR_NOMEM, "Unable to allocate memory for pack_row"); return nerr_pass(err); } static NEOERR *unpack_row (WDB *wdb, void *rdata, int dlen, WDBRow *row) { unsigned char *data = rdata; int version, n; int count, x, ondisk_index, type, d_int, inmem_index; char *s; n = 0; UNPACK_UB4(data, dlen, n, version); switch (version) { case PACK_VERSION_1: UNPACK_UB4(data, dlen, n, count); for (x = 0; xondisk, ondisk_index, NULL); switch (type) { case WDB_TYPE_INT: UNPACK_UB4 (data, dlen, n, d_int); if (inmem_index != 0) row->data[inmem_index-1] = (void *) d_int; break; case WDB_TYPE_STR: UNPACK_STRING (data, dlen, n, s); if (inmem_index != 0) row->data[inmem_index-1] = s; break; default: return nerr_raise (NERR_ASSERT, "Unknown type %d for col %d", type, ondisk_index); } } break; default: return nerr_raise (NERR_ASSERT, "Unknown version %d", version); } return STATUS_OK; pack_err: return nerr_raise(NERR_PARSE, "Unable to unpack row %s", row->key_value); } NEOERR *wdb_column_insert (WDB *wdb, int loc, const char *key, char type) { NEOERR *err; WDBColumn *col, *ocol; int x, len; col = (WDBColumn *) dictSearch (wdb->cols, key, NULL); if (col != NULL) return nerr_raise (NERR_DUPLICATE, "Duplicate key %s:%d", key, col->inmem_index); col = (WDBColumn *) calloc (1, sizeof (WDBColumn)); if (col == NULL) { return nerr_raise (NERR_NOMEM, "Unable to allocate memory for creation of col %s:%d", key, loc); } col->name = strdup(key); if (col->name == NULL) { free(col); return nerr_raise (NERR_NOMEM, "Unable to allocate memory for creation of col %s:%d", key, loc); } col->type = type; col->ondisk_index = wdb->last_ondisk++; /* -1 == append */ if (loc == -1) { err = dictSetValue(wdb->cols, key, col); if (err) { free (col->name); free (col); return nerr_pass_ctx (err, "Unable to insert for creation of col %s:%d", key, loc); } err = uListAppend (wdb->cols_l, (void *)col); if (err) return nerr_pass(err); x = uListLength (wdb->cols_l); col->inmem_index = x; err = skipInsert (wdb->ondisk, col->ondisk_index, (void *)(col->inmem_index), 0); if (err) return nerr_pass_ctx (err, "Unable to update ondisk mapping for %s", key); } else { /* We are inserting this in middle, so the skipList ondisk is now * invalid, as is the inmem_index for all cols */ err = dictSetValue(wdb->cols, key, col); if (err) { free (col->name); free (col); return nerr_pass_ctx (err, "Unable to insert for creation of col %s:%d", key, loc); } err = uListInsert (wdb->cols_l, loc, (void *)col); if (err) return nerr_pass(err); len = uListLength (wdb->cols_l); /* Fix up inmem_index and ondisk skipList */ for (x = 0; x < len; x++) { err = uListGet (wdb->cols_l, x, (void *)&ocol); if (err) return nerr_pass(err); ocol->inmem_index = x + 1; err = skipInsert (wdb->ondisk, ocol->ondisk_index, (void *)(ocol->inmem_index), TRUE); if (err) return nerr_pass_ctx (err, "Unable to update ondisk mapping for %s", key); } } wdb->defn_dirty = 1; wdb->table_version = rand(); return STATUS_OK; } NEOERR *wdb_column_update (WDB *wdb, const char *oldkey, const char *newkey) { WDBColumn *ocol, *col; WDBColumn *vcol; NEOERR *err = STATUS_OK; int x, len, r; ocol = (WDBColumn *) dictSearch (wdb->cols, oldkey, NULL); if (ocol == NULL) return nerr_raise (NERR_NOT_FOUND, "Unable to find column for key %s", oldkey); col = (WDBColumn *) calloc (1, sizeof (WDBColumn)); if (col == NULL) { return nerr_raise (NERR_NOMEM, "Unable to allocate memory for column update %s", newkey); } *col = *ocol; col->name = strdup(newkey); if (col->name == NULL) { free(col); return nerr_raise (NERR_NOMEM, "Unable to allocate memory for column update %s", oldkey); } len = uListLength(wdb->cols_l); for (x = 0; x < len; x++) { err = uListGet (wdb->cols_l, x, (void *)&vcol); if (err) return nerr_pass(err); if (!strcmp(vcol->name, oldkey)) { err = uListSet (wdb->cols_l, x, (void *)col); if (err) return nerr_pass(err); break; } } if (x>len) { return nerr_raise (NERR_ASSERT, "Unable to find cols_l for key %s", oldkey); } r = dictRemove (wdb->cols, oldkey); /* Only failure is key not found */ err = dictSetValue(wdb->cols, newkey, col); if (err) { free (col->name); free (col); return nerr_pass_ctx (err, "Unable to insert for update of col %s->%s", oldkey, newkey); } wdb->defn_dirty = 1; wdb->table_version = rand(); return STATUS_OK; } NEOERR *wdb_column_delete (WDB *wdb, const char *name) { WDBColumn *col; NEOERR *err = STATUS_OK; int len, x, r; len = uListLength(wdb->cols_l); for (x = 0; x < len; x++) { err = uListGet (wdb->cols_l, x, (void *)&col); if (err) return nerr_pass(err); if (!strcmp(col->name, name)) { err = uListDelete (wdb->cols_l, x, NULL); if (err) return nerr_pass(err); break; } } r = dictRemove (wdb->cols, name); /* Only failure is key not found */ if (!r) { return nerr_raise (NERR_NOT_FOUND, "Unable to find column for key %s", name); } wdb->defn_dirty = 1; wdb->table_version = rand(); return STATUS_OK; } NEOERR *wdb_column_exchange (WDB *wdb, const char *key1, const char *key2) { return nerr_raise (NERR_ASSERT, "wdb_column_exchange: Not Implemented"); } /* Not that there's that much point in changing the key name ... */ NEOERR *wdb_update (WDB *wdb, const char *name, const char *key) { if (name != NULL && strcmp(wdb->name, name)) { if (wdb->name != NULL) free(wdb->name); wdb->name = strdup(name); if (wdb->name == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to update name to %s", name); wdb->defn_dirty = 1; wdb->table_version = rand(); } if (key != NULL && strcmp(wdb->key, key)) { if (wdb->key != NULL) free(wdb->key); wdb->key = strdup(key); if (wdb->key == NULL) { wdb->defn_dirty = 0; return nerr_raise (NERR_NOMEM, "Unable to allocate memory to update key to %s", key); } wdb->defn_dirty = 1; wdb->table_version = rand(); } return STATUS_OK; } NEOERR *wdb_create (WDB **wdb, const char *path, const char *name, const char *key, ULIST *col_def, int flags) { WDB *my_wdb; char d_path[_POSIX_PATH_MAX]; NEOERR *err = STATUS_OK; int x, len, r; char *s; *wdb = NULL; err = wdb_alloc (&my_wdb, flags); if (err) return nerr_pass(err); my_wdb->name = strdup (name); my_wdb->key = strdup (key); my_wdb->path = strdup(path); if (my_wdb->name == NULL || my_wdb->key == NULL || my_wdb->path == NULL) { wdb_destroy (&my_wdb); return nerr_raise (NERR_NOMEM, "Unable to allocate memory for creation of %s", name); } /* ondisk must start at one because of skipList */ my_wdb->last_ondisk = 1; len = uListLength(col_def); for (x = 0; x < len; x++) { err = uListGet (col_def, x, (void *)&s); if (err) { wdb_destroy (&my_wdb); return nerr_pass(err); } err = wdb_column_insert (my_wdb, -1, s, WDB_TYPE_STR); my_wdb->defn_dirty = 0; /* So we don't save on error destroy */ if (err) { wdb_destroy (&my_wdb); return nerr_pass(err); } } err = wdb_save_defn (my_wdb, path); if (err) { wdb_destroy (&my_wdb); return nerr_pass(err); } snprintf (d_path, sizeof(d_path), "%s.wdb", path); r = db_open(d_path, DB_BTREE, DB_CREATE | DB_TRUNCATE, 0, NULL, NULL, &(my_wdb->db)); if (r) { wdb_destroy (&my_wdb); return nerr_raise (NERR_DB, "Unable to create db file %s: %d", d_path, r); } *wdb = my_wdb; return STATUS_OK; } NEOERR *wdb_attr_next (WDB *wdb, char **key, char **value) { *value = (char *) dictNext (wdb->attrs, key, NULL); return STATUS_OK; } NEOERR *wdb_attr_get (WDB *wdb, const char *key, char **value) { void *v; v = dictSearch (wdb->attrs, key, NULL); if (v == NULL) return nerr_raise (NERR_NOT_FOUND, "Unable to find attr %s", key); *value = (char *)v; return STATUS_OK; } NEOERR *wdb_attr_set (WDB *wdb, const char *key, const char *value) { NEOERR *err = STATUS_OK; char *v; v = strdup(value); if (v == NULL) return nerr_raise (NERR_NOMEM, "No memory for new attr"); err = dictSetValue(wdb->attrs, key, v); if (err) return nerr_pass_ctx (err, "Unable to set attr %s", key); wdb->defn_dirty = 1; return STATUS_OK; } NEOERR *wdbr_get (WDB *wdb, WDBRow *row, const char *key, void **value) { WDBColumn *col; void *v; col = (WDBColumn *) dictSearch (wdb->cols, key, NULL); if (col == NULL) return nerr_raise (NERR_NOT_FOUND, "Unable to find key %s", key); if (col->inmem_index-1 > row->data_count) return nerr_raise (NERR_ASSERT, "Index for key %s is greater than row data, was table altered?", key); v = row->data[col->inmem_index-1]; *value = v; return STATUS_OK; } NEOERR *wdbr_set (WDB *wdb, WDBRow *row, const char *key, void *value) { WDBColumn *col; col = (WDBColumn *) dictSearch (wdb->cols, key, NULL); if (col == NULL) return nerr_raise (NERR_NOT_FOUND, "Unable to find key %s", key); if (col->inmem_index-1 > row->data_count) return nerr_raise (NERR_ASSERT, "Index for key %s is greater than row data, was table altered?", key); if (col->type == WDB_TYPE_STR && row->data[col->inmem_index-1] != NULL) { free (row->data[col->inmem_index-1]); } row->data[col->inmem_index-1] = value; return STATUS_OK; } static NEOERR *alloc_row (WDB *wdb, WDBRow **row) { WDBRow *my_row; int len; *row = NULL; len = uListLength (wdb->cols_l); my_row = (WDBRow *) calloc (1, sizeof (WDBRow) + len * (sizeof (void *))); if (my_row == NULL) return nerr_raise (NERR_NOMEM, "No memory for new row"); my_row->data_count = len; my_row->table_version = wdb->table_version; *row = my_row; return STATUS_OK; } NEOERR *wdbr_destroy (WDB *wdb, WDBRow **row) { WDBColumn *col; WDBRow *my_row; int len, x; NEOERR *err; err = STATUS_OK; if (*row == NULL) return err; my_row = *row; /* Verify this row maps to this table, or else we could do something * bad */ if (wdb->table_version != my_row->table_version) return nerr_raise (NERR_ASSERT, "Row %s doesn't match current table", my_row->key_value); if (my_row->key_value != NULL) free (my_row->key_value); len = uListLength(wdb->cols_l); for (x = 0; x < len; x++) { if (my_row->data[x] != NULL) { err = uListGet (wdb->cols_l, x, (void *)&col); if (err) break; switch (col->type) { case WDB_TYPE_INT: break; case WDB_TYPE_STR: free (my_row->data[x]); break; default: return nerr_raise (NERR_ASSERT, "Unknown type %d", col->type); } } } free (my_row); *row = NULL; return nerr_pass(err); } NEOERR *wdbr_lookup (WDB *wdb, const char *key, WDBRow **row) { DBT dkey, data; NEOERR *err = STATUS_OK; WDBRow *my_row; int r; *row = NULL; memset(&dkey, 0, sizeof(dkey)); memset(&data, 0, sizeof(data)); dkey.flags = DB_DBT_USERMEM; data.flags = DB_DBT_MALLOC; dkey.data = (void *)key; dkey.size = strlen(key); r = wdb->db->get (wdb->db, NULL, &dkey, &data, 0); if (r == DB_NOTFOUND) return nerr_raise (NERR_NOT_FOUND, "Unable to find key %s", key); else if (r) return nerr_raise (NERR_DB, "Error retrieving key %s: %d", key, r); /* allocate row */ err = alloc_row (wdb, &my_row); if (err != STATUS_OK) { free (data.data); return nerr_pass(err); } my_row->key_value = strdup(key); if (my_row->key_value == NULL) { free (data.data); free (my_row); return nerr_raise (NERR_NOMEM, "No memory for new row"); } /* unpack row */ err = unpack_row (wdb, data.data, data.size, my_row); free (data.data); if (err) { free (my_row); return nerr_pass(err); } *row = my_row; return STATUS_OK; } NEOERR *wdbr_create (WDB *wdb, const char *key, WDBRow **row) { WDBRow *my_row; NEOERR *err = STATUS_OK; *row = NULL; /* allocate row */ err = alloc_row (wdb, &my_row); if (err) return nerr_pass(err); my_row->key_value = strdup(key); if (my_row->key_value == NULL) { wdbr_destroy (wdb, &my_row); return nerr_raise (NERR_NOMEM, "No memory for new row"); } *row = my_row; return STATUS_OK; } NEOERR *wdbr_save (WDB *wdb, WDBRow *row, int flags) { DBT dkey, data; int dflags = 0; NEOERR *err = STATUS_OK; int r; memset(&dkey, 0, sizeof(dkey)); memset(&data, 0, sizeof(data)); dkey.data = row->key_value; dkey.size = strlen(row->key_value); err = pack_row (wdb, row, &(data.data), &data.size); if (err != STATUS_OK) return nerr_pass(err); if (flags & WDBR_INSERT) { dflags = DB_NOOVERWRITE; } r = wdb->db->put (wdb->db, NULL, &dkey, &data, dflags); free (data.data); if (r == DB_KEYEXIST) return nerr_raise (NERR_DUPLICATE, "Key %s already exists", row->key_value); if (r) return nerr_raise (NERR_DB, "Error saving key %s: %d", row->key_value, r); return STATUS_OK; } NEOERR *wdbr_delete (WDB *wdb, const char *key) { DBT dkey; int r; memset(&dkey, 0, sizeof(dkey)); dkey.flags = DB_DBT_USERMEM; dkey.data = (void *)key; dkey.size = strlen(key); r = wdb->db->del (wdb->db, NULL, &dkey, 0); if (r == DB_NOTFOUND) return nerr_raise (NERR_NOT_FOUND, "Key %s not found", key); else if (r) return nerr_raise (NERR_DB, "Error deleting key %s: %d", key, r); return STATUS_OK; } NEOERR *wdbr_dump (WDB *wdb, WDBRow *row) { int x; ne_warn ("version: %d", row->table_version); ne_warn ("key: %s", row->key_value); ne_warn ("count: %d", row->data_count); for (x=0; x < row->data_count; x++) ne_warn ("data[%d]: %s", x, row->data[x]); return STATUS_OK; } NEOERR *wdbc_create (WDB *wdb, WDBCursor **cursor) { DBC *db_cursor; WDBCursor *new_cursor; int r; *cursor = NULL; #if (DB_VERSION_MINOR==4) r = (wdb->db)->cursor (wdb->db, NULL, &db_cursor); #else r = (wdb->db)->cursor (wdb->db, NULL, &db_cursor, 0); #endif if (r) return nerr_raise (NERR_DB, "Unable to create cursor: %d", r); new_cursor = (WDBCursor *) calloc (1, sizeof (WDBCursor)); if (new_cursor == NULL) { db_cursor->c_close (db_cursor); return nerr_raise (NERR_NOMEM, "Unable to create cursor"); } new_cursor->table_version = wdb->table_version; new_cursor->db_cursor = db_cursor; *cursor = new_cursor; return STATUS_OK; } NEOERR *wdbc_destroy (WDB *wdb, WDBCursor **cursor) { if (*cursor != NULL) { (*cursor)->db_cursor->c_close ((*cursor)->db_cursor); free (*cursor); *cursor = NULL; } return STATUS_OK; } NEOERR *wdbr_next (WDB *wdb, WDBCursor *cursor, WDBRow **row, int flags) { DBT dkey, data; WDBRow *my_row; NEOERR *err = STATUS_OK; int r; *row = NULL; if (wdb->table_version != cursor->table_version) { return nerr_raise (NERR_ASSERT, "Cursor doesn't match database"); } memset(&dkey, 0, sizeof(dkey)); memset(&data, 0, sizeof(data)); dkey.flags = DB_DBT_MALLOC; data.flags = DB_DBT_MALLOC; /* First call */ if (flags & WDBC_FIRST) { r = cursor->db_cursor->c_get (cursor->db_cursor, &dkey, &data, DB_FIRST); if (r == DB_NOTFOUND) return nerr_raise (NERR_NOT_FOUND, "Cursor empty"); else if (r) return nerr_raise (NERR_DB, "Unable to get first item from cursor: %d", r); } else { r = cursor->db_cursor->c_get (cursor->db_cursor, &dkey, &data, DB_NEXT); if (r == DB_NOTFOUND) return STATUS_OK; else if (r) return nerr_raise (NERR_DB, "Unable to get next item from cursor: %d", r); } /* allocate row */ err = alloc_row (wdb, &my_row); if (err) { free (data.data); return nerr_pass(err); } my_row->key_value = (char *) malloc (dkey.size + 1); if (my_row->key_value == NULL) { free (data.data); free (my_row); return nerr_raise (NERR_NOMEM, "No memory for new row"); } memcpy (my_row->key_value, dkey.data, dkey.size); my_row->key_value[dkey.size] = '\0'; /* unpack row */ err = unpack_row (wdb, data.data, data.size, my_row); free (data.data); free (dkey.data); if (err) { free (my_row); return nerr_pass(err); } *row = my_row; return STATUS_OK; } NEOERR *wdbr_find (WDB *wdb, WDBCursor *cursor, const char *key, WDBRow **row) { DBT dkey, data; WDBRow *my_row; NEOERR *err = STATUS_OK; int r; *row = NULL; if (wdb->table_version != cursor->table_version) { return nerr_raise (NERR_ASSERT, "Cursor doesn't match database"); } memset(&dkey, 0, sizeof(dkey)); memset(&data, 0, sizeof(data)); dkey.flags = DB_DBT_USERMEM; data.flags = DB_DBT_MALLOC; dkey.data = (void *)key; dkey.size = strlen(key); r = cursor->db_cursor->c_get (cursor->db_cursor, &dkey, &data, DB_SET_RANGE); if (r == DB_NOTFOUND) return STATUS_OK; else if (r) return nerr_raise (r, "Unable to get find item for key %s", key); /* allocate row */ err = alloc_row (wdb, &my_row); if (err) { free (data.data); return nerr_pass(err); } my_row->key_value = (char *) malloc (dkey.size + 1); if (my_row->key_value == NULL) { free (data.data); free (my_row); return nerr_raise (NERR_NOMEM, "No memory for new row"); } memcpy (my_row->key_value, dkey.data, dkey.size); my_row->key_value[dkey.size] = '\0'; /* unpack row */ err = unpack_row (wdb, data.data, data.size, my_row); free (data.data); if (err) { free (my_row); return nerr_pass(err); } *row = my_row; return STATUS_OK; } NEOERR *wdb_keys (WDB *wdb, char **primary_key, ULIST **data) { NEOERR *err; int x, len; WDBColumn *col; ULIST *my_data; char *my_key = NULL; char *my_col = NULL; *data = NULL; *primary_key = NULL; my_key = strdup(wdb->key); if (my_key == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for keys"); len = uListLength(wdb->cols_l); err = uListInit (&my_data, len, 0); if (err != STATUS_OK) { free(my_key); return nerr_pass(err); } for (x = 0; x < len; x++) { err = uListGet (wdb->cols_l, x, (void *)&col); if (err) goto key_err; my_col = strdup(col->name); if (my_col == NULL) { err = nerr_raise (NERR_NOMEM, "Unable to allocate memory for keys"); goto key_err; } err = uListAppend (my_data, my_col); my_col = NULL; if (err) goto key_err; } *data = my_data; *primary_key = my_key; return STATUS_OK; key_err: if (my_key != NULL) free (my_key); if (my_col != NULL) free (my_col); *primary_key = NULL; uListDestroy (&my_data, 0); return nerr_pass(err); } /* * Known Issues: * - Probably need to store the actual key value in the packed row.. * Maybe not, because any cursor you use on a sleepycat db will * return the key... * - um, memory. Especially when dealing with rows, need to keep track * of when we allocate, when we dealloc, and who owns that memory to * free it * - function to delete entry from wdb */ clearsilver-0.10.5/util/wdb.h0000644001211700116100000000707310261042731012731 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __WDB_H_ #define __WDB_H_ 1 #include "util/skiplist.h" #include "util/dict.h" #include "util/ulist.h" #include typedef struct _column { char *name; int ondisk_index; /* index# on disk, constant for life of db, must be 1 or higher */ int inmem_index; /* load time specific, needs to be flushed on alter table */ char type; } WDBColumn; typedef struct _row { int table_version; /* random number which maps to the same number of the table defn when loaded to verify they match */ char *key_value; int data_count; void *data[1]; } WDBRow; typedef struct _cursor { int table_version; /* random number which maps to the same number of the table defn when loaded to verify they match */ DBC *db_cursor; } WDBCursor; typedef struct _wdb { char *name; char *key; char *path; dictCtx attrs; dictCtx cols; skipList ondisk; ULIST *cols_l; DB *db; int last_ondisk; int defn_dirty; /* must save defn on destroy */ int table_version; /* random number which maps to the same number of the table defn when loaded/changed to verify they match */ } WDB; #define WDB_TYPE_STR 's' #define WDB_TYPE_INT 'i' #define WDBC_FIRST (1<<0) #define WDBC_NEXT (1<<1) #define WDBC_FIND (1<<2) #define WDBR_INSERT (1<<0) NEOERR * wdb_open (WDB **wdb, const char *name, int flags); NEOERR * wdb_save (WDB *wdb); NEOERR * wdb_update (WDB *wdb, const char *name, const char *key); NEOERR * wdb_create (WDB **wdb, const char *path, const char *name, const char *key, ULIST *col_def, int flags); void wdb_destroy (WDB **wdb); NEOERR * wdb_column_insert (WDB *wdb, int loc, const char *key, char type); NEOERR * wdb_column_delete (WDB *wdb, const char *name); NEOERR * wdb_column_update (WDB *wdb, const char *oldkey, const char *newkey); NEOERR * wdb_column_exchange (WDB *wdb, const char *key1, const char *key2); /* * function: wdb_keys * description: this function returns the key and column names for the * current database * input: wdb - open database * output: primary_key - pointer to the primary key * data - pointer to a ULIST of the columns. * both of these are allocated structures, you can clear data * with uListDestroy (data, ULIST_FREE) * return: STATUS_OK on no error or egerr.h error */ NEOERR * wdb_keys (WDB *wdb, char **primary_key, ULIST **data); NEOERR * wdb_attr_get (WDB *wdb, const char *key, char **value); NEOERR * wdb_attr_set (WDB *wdb, const char *key, const char *value); NEOERR * wdb_attr_next (WDB *wdb, char **key, char **value); NEOERR * wdbr_lookup (WDB *wdb, const char *key, WDBRow **row); NEOERR * wdbr_create (WDB *wdb, const char *key, WDBRow **row); NEOERR * wdbr_save (WDB *wdb, WDBRow *row, int flags); NEOERR * wdbr_delete (WDB *wdb, const char *key); NEOERR * wdbr_destroy (WDB *wdb, WDBRow **row); NEOERR * wdbr_get (WDB *wdb, WDBRow *row, const char *key, void **value); NEOERR * wdbr_set (WDB *wdb, WDBRow *row, const char *key, void *value); NEOERR * wdbr_dump (WDB *wdb, WDBRow *row); NEOERR * wdbr_next (WDB *wdb, WDBCursor *cursor, WDBRow **row, int flags); NEOERR * wdbr_find (WDB *wdb, WDBCursor *cursor, const char *key, WDBRow **row); NEOERR * wdbc_create (WDB *wdb, WDBCursor **cursor); NEOERR * wdbc_destroy (WDB *wdb, WDBCursor **cursor); #endif /* __WDB_H_ */ clearsilver-0.10.5/util/wildmat.c0000644001211700116100000001312410261043027013602 00000000000000/* $Revision: 1.2 $ ** ** Do shell-style pattern matching for ?, \, [], and * characters. ** Might not be robust in face of malformed patterns; e.g., "foo[a-" ** could cause a segmentation violation. It is 8bit clean. ** ** Written by Rich $alz, mirror!rs, Wed Nov 26 19:03:17 EST 1986. ** Rich $alz is now . ** April, 1991: Replaced mutually-recursive calls with in-line code ** for the star character. ** ** Special thanks to Lars Mathiesen for the ABORT code. ** This can greatly speed up failing wildcard patterns. For example: ** pattern: -*-*-*-*-*-*-12-*-*-*-m-*-*-* ** text 1: -adobe-courier-bold-o-normal--12-120-75-75-m-70-iso8859-1 ** text 2: -adobe-courier-bold-o-normal--12-120-75-75-X-70-iso8859-1 ** Text 1 matches with 51 calls, while text 2 fails with 54 calls. Without ** the ABORT code, it takes 22310 calls to fail. Ugh. The following ** explanation is from Lars: ** The precondition that must be fulfilled is that DoMatch will consume ** at least one character in text. This is true if *p is neither '*' nor ** '\0'.) The last return has ABORT instead of FALSE to avoid quadratic ** behaviour in cases like pattern "*a*b*c*d" with text "abcxxxxx". With ** FALSE, each star-loop has to run to the end of the text; with ABORT ** only the last one does. ** ** Once the control of one instance of DoMatch enters the star-loop, that ** instance will return either TRUE or ABORT, and any calling instance ** will therefore return immediately after (without calling recursively ** again). In effect, only one star-loop is ever active. It would be ** possible to modify the code to maintain this context explicitly, ** eliminating all recursive calls at the cost of some complication and ** loss of clarity (and the ABORT stuff seems to be unclear enough by ** itself). I think it would be unwise to try to get this into a ** released version unless you have a good test data base to try it ** out on. */ #include "cs_config.h" #include #include "neo_misc.h" #define ABORT -1 /* What character marks an inverted character class? */ #define NEGATE_CLASS '^' /* Is "*" a common pattern? */ #define OPTIMIZE_JUST_STAR /* Do tar(1) matching rules, which ignore a trailing slash? */ #undef MATCH_TAR_PATTERN /* ** Match text and p, return TRUE, FALSE, or ABORT. */ static int DoMatch(register const char *text, register const char *p) { register int last; register int matched; register int reverse; for ( ; *p; text++, p++) { if (*text == '\0' && *p != '*') return ABORT; switch (*p) { case '\\': /* Literal match with following character. */ p++; /* FALLTHROUGH */ default: if (*text != *p) return FALSE; continue; case '?': /* Match anything. */ continue; case '*': while (*++p == '*') /* Consecutive stars act just like one. */ continue; if (*p == '\0') /* Trailing star matches everything. */ return TRUE; while (*text) if ((matched = DoMatch(text++, p)) != FALSE) return matched; return ABORT; case '[': reverse = p[1] == NEGATE_CLASS ? TRUE : FALSE; if (reverse) /* Inverted character class. */ p++; matched = FALSE; if (p[1] == ']' || p[1] == '-') if (*++p == *text) matched = TRUE; for (last = *p; *++p && *p != ']'; last = *p) /* This next line requires a good C compiler. */ if (*p == '-' && p[1] != ']' ? *text <= *++p && *text >= last : *text == *p) matched = TRUE; if (matched == reverse) return FALSE; continue; } } #ifdef MATCH_TAR_PATTERN if (*text == '/') return TRUE; #endif /* MATCH_TAR_ATTERN */ return *text == '\0'; } /* ** Match text and p, return TRUE, FALSE, or ABORT. */ static int DoMatchCaseInsensitive(register const char *text, register const char *p) { register int last; register int matched; register int reverse; for ( ; *p; text++, p++) { if (*text == '\0' && *p != '*') return ABORT; switch (*p) { case '\\': /* Literal match with following character. */ p++; /* FALLTHROUGH */ default: if (toupper(*text) != toupper(*p)) return FALSE; continue; case '?': /* Match anything. */ continue; case '*': while (*++p == '*') /* Consecutive stars act just like one. */ continue; if (*p == '\0') /* Trailing star matches everything. */ return TRUE; while (*text) if ((matched = DoMatchCaseInsensitive(text++, p)) != FALSE) return matched; return ABORT; case '[': reverse = p[1] == NEGATE_CLASS ? TRUE : FALSE; if (reverse) /* Inverted character class. */ p++; matched = FALSE; if (p[1] == ']' || p[1] == '-') if (toupper(*++p) == toupper(*text)) matched = TRUE; for (last = toupper(*p); *++p && *p != ']'; last = toupper(*p)) /* This next line requires a good C compiler. */ if (*p == '-' && p[1] != ']' ? toupper(*text) <= toupper(*++p) && toupper(*text) >= last : toupper(*text) == toupper(*p)) matched = TRUE; if (matched == reverse) return FALSE; continue; } } #ifdef MATCH_TAR_PATTERN if (*text == '/') return TRUE; #endif /* MATCH_TAR_ATTERN */ return *text == '\0'; } /* ** User-level routine. Returns TRUE or FALSE. */ int wildmat(const char *text, const char *p) { #ifdef OPTIMIZE_JUST_STAR if (p[0] == '*' && p[1] == '\0') return TRUE; #endif /* OPTIMIZE_JUST_STAR */ return DoMatch(text, p) == TRUE; } /* ** User-level routine. Returns TRUE or FALSE. */ int wildmatcase(const char *text, const char *p) { #ifdef OPTIMIZE_JUST_STAR if (p[0] == '*' && p[1] == '\0') return TRUE; #endif /* OPTIMIZE_JUST_STAR */ return DoMatchCaseInsensitive(text, p) == TRUE; } clearsilver-0.10.5/util/wildmat.h0000644001211700116100000000040410261043036013604 00000000000000/* * Copyright (C) 1986-1991 Rich Salz * */ #ifndef __WILDMAT_H_ #define __WILDMAT_H_ 1 __BEGIN_DECLS int wildmat(const char *text, const char *p); int wildmatcase(const char *text, const char *p); __END_DECLS #endif /* __WILDMAT_H_ */ clearsilver-0.10.5/cs/0000755001211700116100000000000010645505044011514 500000000000000clearsilver-0.10.5/cs/Makefile0000644001211700116100000000526010616225357013103 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk CS_LIB = $(LIB_DIR)libneo_cs.a CS_SRC = csparse.c CS_OBJ = $(CS_SRC:%.c=%.o) CSTEST_EXE = cstest CSTEST_SRC = cstest.c CSTEST_OBJ = $(CSTEST_SRC:%.c=%.o) CSR_EXE = cs CSR_SRC = cs.c CSR_OBJ = $(CSR_SRC:%.c=%.o) CSDUMP_EXE = csdump CSDUMP_SRC = csdump.c CSDUMP_OBJ = $(CSDUMP_SRC:%.c=%.o) LIBS += -lneo_cs -lneo_utl # -lefence TARGETS = $(CS_LIB) $(CSTEST_EXE) $(CSR_EXE) test CS_TESTS = test.cs test2.cs test3.cs test4.cs test5.cs test6.cs test7.cs \ test8.cs test9.cs test10.cs test11.cs test12.cs test13.cs \ test14.cs test15.cs test16.cs test17.cs test18.cs test19.cs \ test_var.cs test_paren.cs test_chuck.cs test_trak1.cs test_iter.cs \ test_each_array.cs test_name.cs test_with.cs test_numbers.cs \ test_splice.cs test_joo.cs test_first_last.cs test_abs_max_min.cs \ test_comma.cs test_macro_set.cs test_func.cs test_escape.cs \ test_uvar.cs test_crc.cs all: $(TARGETS) $(CS_LIB): $(CS_OBJ) $(AR) $@ $(CS_OBJ) $(RANLIB) $@ $(CSTEST_EXE): $(CSTEST_OBJ) $(CS_LIB) $(LD) $@ $(CSTEST_OBJ) $(LDFLAGS) $(LIBS) # -lefence $(CSR_EXE): $(CSR_OBJ) $(CS_LIB) $(LD) $@ $(CSR_OBJ) $(LDFLAGS) $(LIBS) # -lefence $(CSDUMP_EXE): $(CSDUMP_OBJ) $(CS_LIB) $(LD) $@ $(CSDUMP_OBJ) $(LDFLAGS) $(LIBS) ## BE VERY CAREFUL WHEN REGENERATING THESE gold: $(CSTEST_EXE) @for test in $(CS_TESTS); do \ rm -f $$test.gold; \ ./cstest test.hdf $$test > $$test.gold; \ done; \ ./cstest test_tag.hdf test_tag.cs > test_tag.cs.gold @echo "Generated Gold Files" test: $(CSTEST_EXE) $(CS_TESTS) @echo "Running cs regression tests" @failed=0; \ for test in $(CS_TESTS); do \ rm -f $$test.out; \ ./cstest test.hdf $$test > $$test.out 2>&1; \ diff $$test.out $$test.gold 2>&1 > /dev/null; \ return_code=$$?; \ if [ $$return_code -ne 0 ]; then \ diff $$test.gold $$test.out > $$test.err; \ echo "Failed Regression Test: $$test"; \ echo " See $$test.out and $$test.err"; \ failed=1; \ fi; \ done; \ rm -f test_tag.cs.out; \ ./cstest test_tag.hdf test_tag.cs> test_tag.cs.out 2>&1; \ diff test_tag.cs.out test_tag.cs.gold; \ return_code=$$?; \ if [ $$return_code -ne 0 ]; then \ echo "Failed Regression Test: test_tag.cs"; \ failed=1; \ fi; \ if [ $$failed -eq 1 ]; then \ exit 1; \ fi; @touch test @echo "Passed" install: all $(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(cs_includedir)/cs $(INSTALL) -m 644 cs.h $(DESTDIR)$(cs_includedir)/cs $(INSTALL) -m 644 $(CS_LIB) $(DESTDIR)$(libdir) $(INSTALL) $(CSTEST_EXE) $(DESTDIR)$(bindir) $(INSTALL) $(CSR_EXE) $(DESTDIR)$(bindir) clean: $(RM) core *.o distclean: $(RM) Makefile.depends $(TARGETS) core *.o *.out clearsilver-0.10.5/cs/cs.c0000644001211700116100000000406010261037505012201 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include #include #include #include "cs.h" #include "util/neo_misc.h" #include "util/neo_hdf.h" static NEOERR *output (void *ctx, char *s) { printf ("%s", s); return STATUS_OK; } int main (int argc, char *argv[]) { NEOERR *err; CSPARSE *parse; HDF *hdf; int verbose = 0; char *hdf_file, *cs_file; char c; extern char *optarg; err = hdf_init(&hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = cs_init (&parse, hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } while ((c = getopt(argc, argv, "Hvh:c:")) != EOF ) switch (c) { case 'h': hdf_file=optarg; err = hdf_read_file(hdf, hdf_file); if (err != STATUS_OK) { nerr_log_error(err); return -1; } break; case 'c': cs_file=optarg; if ( verbose ) printf ("Parsing %s\n", cs_file); err = cs_parse_file (parse, cs_file); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } break; case 'v': verbose=1; break; case 'H': fprintf(stderr, "Usage: %s [-v] [-h ] [-c ]\n", argv[0]); fprintf(stderr, " -h load hdf file file.hdf (multiple allowed)\n"); fprintf(stderr, " -c load cs file file.cs (multiple allowed)\n"); fprintf(stderr, " -v verbose output\n"); return -1; break; } err = cs_render(parse, NULL, output); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } if (verbose) { printf ("\n-----------------------\nCS DUMP\n"); err = cs_dump(parse, NULL, output); } cs_destroy (&parse); if (verbose) { printf ("\n-----------------------\nHDF DUMP\n"); hdf_dump (hdf, NULL); } return 0; } clearsilver-0.10.5/cs/cs.h0000644001211700116100000004302710640326601012213 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * CS Syntax (pseudo BNF, pseudo accurate) * ------------------------------------------------------------------ * CS := (ANYTHING COMMAND)* * CS_OPEN := * COMMAND := (CMD_IF | CMD_VAR | CMD_EVAR | CMD_INCLUDE | CMD_EACH * | CMD_DEF | CMD_CALL | CMD_SET | CMD_LOOP ) * CMD_IF := CS_OPEN IF CS_CLOSE CS CMD_ENDIF * CMD_ENDIF := CS_OPEN ENDIF CS_CLOSE * CMD_INCLUDE := CS_OPEN INCLUDE CS_CLOSE * CMD_DEF := CS_OPEN DEF CS_CLOSE * CMD_CALL := CS_OPEN CALL CS_CLOSE * CMD_SET := CS_OPEN SET CS_CLOSE * CMD_LOOP := CS_OPEN LOOP CS_CLOSE * LOOP := loop:VAR = EXPR, EXPR, EXPR * SET := set:VAR = EXPR * EXPR := (ARG | ARG OP EXPR) * CALL := call:VAR LPAREN ARG (,ARG)* RPAREN * DEF := def:VAR LPAREN ARG (,ARG)* RPAREN * INCLUDE := include:(VAR|STRING) * IF := (if:ARG OP ARG|if:ARG|if:!ARG) * ENDIF := /if * OP := ( == | != | < | <= | > | >= | || | && | + | - | * | / | % ) * ARG := (STRING|VAR|NUM) * STRING := "[^"]" * VAR := [^"<> ]+ * NUM := #[0-9]+ */ #ifndef __CSHDF_H_ #define __CSHDF_H_ 1 #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/ulist.h" #include "util/neo_hdf.h" #include "util/neo_str.h" __BEGIN_DECLS typedef enum { /* Unary operators */ CS_OP_NONE = (1<<0), CS_OP_EXISTS = (1<<1), CS_OP_NOT = (1<<2), CS_OP_NUM = (1<<3), /* Binary Operators */ CS_OP_EQUAL = (1<<4), CS_OP_NEQUAL = (1<<5), CS_OP_LT = (1<<6), CS_OP_LTE = (1<<7), CS_OP_GT = (1<<8), CS_OP_GTE = (1<<9), CS_OP_AND = (1<<10), CS_OP_OR = (1<<11), CS_OP_ADD = (1<<12), CS_OP_SUB = (1<<13), CS_OP_MULT = (1<<14), CS_OP_DIV = (1<<15), CS_OP_MOD = (1<<16), /* Associative Operators */ CS_OP_LPAREN = (1<<17), CS_OP_RPAREN = (1<<18), CS_OP_LBRACKET = (1<<19), CS_OP_RBRACKET = (1<<20), CS_OP_DOT = (1<<21), CS_OP_COMMA = (1<<22), /* Types */ CS_TYPE_STRING = (1<<25), CS_TYPE_NUM = (1<<26), CS_TYPE_VAR = (1<<27), CS_TYPE_VAR_NUM = (1<<28), /* Not real types... */ CS_TYPE_MACRO = (1<<29), CS_TYPE_FUNCTION = (1<<30) } CSTOKEN_TYPE; #define CS_OPS_UNARY (CS_OP_EXISTS | CS_OP_NOT | CS_OP_NUM | CS_OP_LPAREN) #define CS_TYPES (CS_TYPE_STRING | CS_TYPE_NUM | CS_TYPE_VAR | CS_TYPE_VAR_NUM) #define CS_OPS_LVALUE (CS_OP_DOT | CS_OP_LBRACKET | CS_TYPES) #define CS_TYPES_VAR (CS_TYPE_VAR | CS_TYPE_VAR_NUM) #define CS_TYPES_CONST (CS_TYPE_STRING | CS_TYPE_NUM) #define CS_ASSOC (CS_OP_RPAREN | CS_OP_RBRACKET) typedef struct _parse CSPARSE; typedef struct _funct CS_FUNCTION; typedef struct _escape_context CS_ECONTEXT; typedef struct _position CS_POSITION; typedef struct _error CS_ERROR; typedef struct _arg { CSTOKEN_TYPE op_type; char *argexpr; char *s; long int n; int alloc; struct _funct *function; struct _macro *macro; struct _arg *expr1; struct _arg *expr2; struct _arg *next; } CSARG; #define CSF_REQUIRED (1<<0) typedef struct _tree { int node_num; int cmd; int flags; NEOS_ESCAPE escape; CSARG arg1; CSARG arg2; CSARG *vargs; char *fname; int linenum; int colnum; struct _tree *case_0; struct _tree *case_1; struct _tree *next; } CSTREE; typedef struct _local_map { CSTOKEN_TYPE type; char *name; int map_alloc; /* These three (s,n,h) used to be a union, but now we sometimes allocate * a buffer in s with the "string" value of n, so its separate */ char *s; long int n; HDF *h; int first; /* This local is the "first" item in an each/loop */ int last; /* This local is the "last" item in an loop, each is calculated explicitly based on hdf_obj_next() in _builtin_last() */ struct _local_map *next; } CS_LOCAL_MAP; typedef struct _macro { char *name; int n_args; CSARG *args; CSTREE *tree; struct _macro *next; } CS_MACRO; /* CSOUTFUNC is a callback function for where cs_render will render the * template to. * Technically, the char * for this func should be const char *, but that * would break existing code. */ typedef NEOERR* (*CSOUTFUNC)(void *, char *); /* CSFUNCTION is a callback function used for handling a function made * available inside the template. Used by cs_register_function. Exposed * here as part of the experimental extension framework, this may change * in future versions. */ typedef NEOERR* (*CSFUNCTION)(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result); /* CSSTRFUNC is a callback function for the more limited "string filter" * function handling. String filters only take a string and return a * string and have no "data" that is passed back, attempting to make them * "safe" from extensions that might try to do silly things like SQL queries. * */ typedef NEOERR* (*CSSTRFUNC)(const char *str, char **ret); /* CSFILELOAD is a callback function to intercept file load requests and * provide templates via another mechanism. This way you can load templates * that you compiled-into your binary, from in-memory caches, or from a * zip file, etc. The HDF is provided so you can choose to use the * hdf_search_path function to find the file. contents should return * a full malloc copy of the contents of the file, which the parser will modify * and own and free. Use cs_register_fileload to set this function for * your CSPARSE context. */ typedef NEOERR* (*CSFILELOAD)(void *ctx, HDF *hdf, const char *filename, char **contents); struct _funct { char *name; int name_len; int n_args; NEOS_ESCAPE escape; /* States escaping exemptions. default: NONE. */ CSFUNCTION function; CSSTRFUNC str_func; struct _funct *next; }; /* This structure maintains the necessary running state to manage * automatic escaping in tandem with the 'escape' directive. It is passed * around inside _parse. */ struct _escape_context { NEOS_ESCAPE global_ctx; /* Contains global default escaping mode: none,html,js,url */ NEOS_ESCAPE current; /* Used to pass around parse and evaluation specific data from subfunctions upward. */ NEOS_ESCAPE next_stack; /* This is a big fat workaround. Since STACK_ENTRYs are only added to the stack after the command[].parse_handler() is called for the call it is being setup for, this is used to pass state forward. E.g. This is used for 'def' to set UNDEF escaping state to delay escaping status to evaluation time. */ NEOS_ESCAPE when_undef; /* Contains the escaping context to be used when a UNDEF is being replaced at evaluation time. E.g. this is set in call_eval to force the macro code to get call's parsing context at eval time. */ }; /* This structure is used to track current location within the CS file being * parsed. This information is used to find the filename and line number for * each node. */ struct _position { int line; /* Line number for current position */ int col; /* Column number for current position */ int cur_offset; /* The current position - commence reading from here */ }; struct _error { NEOERR *err; struct _error *next; }; struct _parse { const char *context; /* A string identifying where the parser is parsing */ int in_file; /* Indicates if current context is a file */ int offset; int audit_mode; /* If in audit_mode, gather some extra information */ CS_POSITION pos; /* Container for current position in CS file */ CS_ERROR *err_list; /* List of non-fatal errors encountered */ char *context_string; CS_ECONTEXT escaping; /* Context container for escape data */ char *tag; /* Usually cs, but can be set via HDF Config.TagStart */ int taglen; ULIST *stack; ULIST *alloc; /* list of strings owned by CSPARSE and free'd when its destroyed */ CSTREE *tree; CSTREE *current; CSTREE **next; HDF *hdf; struct _parse *parent; /* set on internally created parse instances to point at the parent. This can be used for hierarchical scope in the future. */ CS_LOCAL_MAP *locals; CS_MACRO *macros; CS_FUNCTION *functions; /* Output */ void *output_ctx; CSOUTFUNC output_cb; void *fileload_ctx; CSFILELOAD fileload; /* Global hdf struct */ /* smarti: Added for support for global hdf under local hdf */ HDF *global_hdf; }; /* * Function: cs_init - create and initialize a CS context * Description: cs_init will create a CSPARSE structure and initialize * it. This structure maintains the state and information * necessary for parsing and rendering a CS template. * Input: parse - a pointer to a pointer to a CSPARSE structure that * will be created * hdf - the HDF dataset to be used during parsing and rendering * Output: parse will contain a pointer to the allocated CSPARSE * structure. This structure will be deallocated with * cs_destroy() * Return: NERR_NOMEM * MT-Level: cs routines perform no locking, and neither do hdf * routines. They should be safe in an MT environment as long * as they are confined to a single thread. */ NEOERR *cs_init (CSPARSE **parse, HDF *hdf); /* * Function: cs_parse_file - parse a CS template file * Description: cs_parse_file will parse the CS template located at * path. It will use hdf_search_path() if path does not * begin with a '/'. The parsed CS template will be * appended to the current parse tree stored in the CSPARSE * structure. The entire file is loaded into memory and * parsed in place. * Input: parse - a CSPARSE structure created with cs_init * path - the path to the file to parse * Output: None * Return: NERR_ASSERT - if path == NULL * NERR_NOT_FOUND - if path isn't found * NERR_SYSTEM - if path can't be accessed * NERR_NOMEM - unable to allocate memory to load file into memory * NERR_PARSE - error in CS template */ NEOERR *cs_parse_file (CSPARSE *parse, const char *path); /* * Function: cs_parse_string - parse a CS template string * Description: cs_parse_string parses a string. The string is * modified, and internal references are kept by the parse * tree. For this reason, ownership of the string is * transfered to the CS system, and the string will be * free'd when cs_destroy() is called. * The parse information will be appended to the current * parse tree. During parse, the only HDF variables which * are evaluated are those used in evar or include * statements. * Input: parse - a CSPARSE structure created with cs_init * buf - the string to parse. Embedded NULLs are not currently * supported * blen - the length of the string * Output: None * Return: NERR_PARSE - error in CS template * NERR_NOMEM - unable to allocate memory for parse structures * NERR_NOT_FOUND - missing required variable */ NEOERR *cs_parse_string (CSPARSE *parse, char *buf, size_t blen); /* * Function: cs_render - render a CS parse tree * Description: cs_render will evaluate a CS parse tree, calling the * CSOUTFUNC passed to it for output. Note that calling * cs_render multiple times on the same parse tree may or * may not render the same output as the set statement has * side-effects, it updates the HDF data used by the * render. Typically, you will call one of the cs_parse * functions before calling this function. * Input: parse - the CSPARSE structure containing the CS parse tree * that will be evaluated * ctx - user data that will be passed as the first variable to * the CSOUTFUNC. * cb - a CSOUTFUNC called to render the output. A CSOUTFUNC is * defined as: * typedef NEOERR* (*CSOUTFUNC)(void *, char *); * Output: None * Return: NERR_NOMEM - Unable to allocate memory for CALL or SET * functions * any error your callback functions returns */ NEOERR *cs_render (CSPARSE *parse, void *ctx, CSOUTFUNC cb); /* * Function: cs_dump - dump the cs parse tree * Description: cs_dump will dump the CS parse tree in the parse struct. * This can be useful for debugging your templates. * This function also uses the CSOUTFUNC callback to * display the parse tree. * Input: parse - the CSPARSE structure created with cs_init * ctx - user data to be passed to the CSOUTFUNC * cb - a CSOUTFUNC callback * Output: None * Return: NERR_ASSERT if there is no parse tree * anything your CSOUTFUNC may return */ NEOERR *cs_dump (CSPARSE *parse, void *ctx, CSOUTFUNC cb); /* * Function: cs_destroy - clean up and dealloc a parse tree * Description: cs_destroy will clean up all the memory associated with * a CSPARSE structure, including strings passed to * cs_parse_string. This does not clean up any memory * allocated by your own CSOUTFUNC or the HDF data * structure passed to cs_init. It is safe to call this * with a NULL pointer, and it will leave parse NULL as * well (ie, it can be called more than once on the same * var) * Input: parse - a pointer to a parse structure. * Output: parse - will be NULL * Return: None */ void cs_destroy (CSPARSE **parse); /* * Function: cs_register_fileload - register a fileload function * Description: cs_register_fileload registers a fileload function that * overrides the built-in function. The built-in function * uses hdf_search_path and ne_file_load (based on stat/open/read) * to find and load the file on every template render. * You can override this function if you wish to provide * other template search functions, or load the template * from an in-memory cache, etc. * This fileload function will be used by cs_parse, including * any include: commands in the template. * Input: parse - a pointer to an initialized CSPARSE structure * ctx - pointer that is passed to the CSFILELOAD function when called * fileload - a CSFILELOAD function * Output: None * Return: None * */ void cs_register_fileload(CSPARSE *parse, void *ctx, CSFILELOAD fileload); /* * Function: cs_register_strfunc - register a string handling function * Description: cs_register_strfunc will register a string function that * can be called during CS render. This not-callback is * designed to allow for string formating/escaping * functions that are not built-in to CS (since CS is not * HTML specific, for instance, but it is very useful to * have CS have functions for javascript/html/url * escaping). Note that we explicitly don't provide any * associated data or anything to attempt to keep you from * using this as a generic callback... * The format of a CSSTRFUNC is: * NEOERR * str_func(char *in, char **out); * This function should not modify the input string, and * should allocate the output string with a libc function. * (as we will call free on it) * Input: parse - a pointer to a CSPARSE structure initialized with cs_init() * funcname - the name for the CS function call * Note that registering a duplicate funcname will * raise a NERR_DUPLICATE error * str_func - a CSSTRFUNC not-callback * Return: NERR_NOMEM - failure to allocate any memory for data structures * NERR_DUPLICATE - funcname already registered * */ NEOERR *cs_register_strfunc(CSPARSE *parse, char *funcname, CSSTRFUNC str_func); /* * Function: cs_register_esc_strfunc - cs_register_strfunc with escaping context * Description: cs_register_esc_strfunc functions exactly as cs_register_strfunc * except that it changes the evaluation escaping context to disable * default escaping. * Input: parse - a pointer to a CSPARSE structure initialized with cs_init() * funcname - the name for the CS function call * Note that registering a duplicate funcname will * raise a NERR_DUPLICATE error * str_func - a CSSTRFUNC not-callback * Return: NERR_NOMEM - failure to allocate any memory for data structures * NERR_DUPLICATE - funcname already registered * */ NEOERR *cs_register_esc_strfunc(CSPARSE *parse, char *funcname, CSSTRFUNC str_func); /* Testing functions for future function api. This api may change in the * future. */ NEOERR *cs_arg_parse(CSPARSE *parse, CSARG *args, const char *fmt, ...); NEOERR *cs_arg_parsev(CSPARSE *parse, CSARG *args, const char *fmt, va_list ap); NEOERR *cs_register_function(CSPARSE *parse, const char *funcname, int n_args, CSFUNCTION function); __END_DECLS #endif /* __CSHDF_H_ */ clearsilver-0.10.5/cs/csdump.c0000644001211700116100000000204010261037505013063 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include "cs.h" #include "util/neo_misc.h" #include "util/neo_hdf.h" /* static NEOERR *output (void *ctx, char *s) { printf ("%s", s); return STATUS_OK; } */ int main (int argc, char *argv[]) { NEOERR *err; CSPARSE *parse; HDF *hdf; if (argc < 3) { ne_warn ("Usage: csdump "); return -1; } err = hdf_init(&hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } ne_warn ("Parsing %s", argv[1]); err = cs_init (&parse, hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = cs_parse_file (parse, argv[1]); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } err = cs_dump_c(parse, argv[2]); cs_destroy (&parse); return 0; } clearsilver-0.10.5/cs/csparse.c0000644001211700116100000033443410645311756013260 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * TODO: there is some really ugly pseudo reference counting in here * for allocation of temporary strings (and passing references). See the alloc * member of various structs for details. We should move this to an arena * allocator so we can just allocate whenever we need to and just clean up * all the allocation at the end (may require two arenas: one for parese and * one for render) */ #include "cs_config.h" #include #include #include #include #include #include #include #include #include #include #include #ifdef ENABLE_GETTEXT #include #endif #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_files.h" #include "util/neo_str.h" #include "util/ulist.h" #include "cs.h" /* turn on some debug output for expressions */ #define DEBUG_EXPR_PARSE 0 #define DEBUG_EXPR_EVAL 0 typedef enum { ST_SAME = 0, ST_GLOBAL = 1<<0, ST_IF = 1<<1, ST_ELSE = 1<<2, ST_EACH = 1<<3, ST_WITH = 1<<4, ST_POP = 1<<5, ST_DEF = 1<<6, ST_LOOP = 1<<7, ST_ALT = 1<<8, ST_ESCAPE = 1<<9, } CS_STATE; #define ST_ANYWHERE (ST_EACH | ST_WITH | ST_ELSE | ST_IF | ST_GLOBAL | ST_DEF | ST_LOOP | ST_ALT | ST_ESCAPE) typedef struct _stack_entry { CS_STATE state; NEOS_ESCAPE escape; CSTREE *tree; CSTREE *next_tree; int num_local; int location; } STACK_ENTRY; static NEOERR *literal_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *literal_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *name_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *name_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *var_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *var_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *evar_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *lvar_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *lvar_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *if_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *if_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *else_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *elif_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *endif_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *each_with_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *each_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *with_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *end_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *include_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *linclude_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *linclude_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *def_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *skip_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *call_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *call_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *set_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *set_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *loop_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *loop_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *alt_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *alt_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *escape_parse (CSPARSE *parse, int cmd, char *arg); static NEOERR *escape_eval (CSPARSE *parse, CSTREE *node, CSTREE **next); static NEOERR *render_node (CSPARSE *parse, CSTREE *node); static NEOERR *cs_init_internal (CSPARSE **parse, HDF *hdf, CSPARSE *parent); static int rearrange_for_call(CSARG **args); typedef struct _cmds { char *cmd; int cmdlen; CS_STATE allowed_state; CS_STATE next_state; NEOERR* (*parse_handler)(CSPARSE *parse, int cmd, char *arg); NEOERR* (*eval_handler)(CSPARSE *parse, CSTREE *node, CSTREE **next); int has_arg; } CS_CMDS; CS_CMDS Commands[] = { {"literal", sizeof("literal")-1, ST_ANYWHERE, ST_SAME, literal_parse, literal_eval, 0}, {"name", sizeof("name")-1, ST_ANYWHERE, ST_SAME, name_parse, name_eval, 1}, {"var", sizeof("var")-1, ST_ANYWHERE, ST_SAME, var_parse, var_eval, 1}, {"uvar", sizeof("uvar")-1, ST_ANYWHERE, ST_SAME, var_parse, var_eval, 1}, {"evar", sizeof("evar")-1, ST_ANYWHERE, ST_SAME, evar_parse, skip_eval, 1}, {"lvar", sizeof("lvar")-1, ST_ANYWHERE, ST_SAME, lvar_parse, lvar_eval, 1}, {"if", sizeof("if")-1, ST_ANYWHERE, ST_IF, if_parse, if_eval, 1}, {"else", sizeof("else")-1, ST_IF, ST_POP | ST_ELSE, else_parse, skip_eval, 0}, {"elseif", sizeof("elseif")-1, ST_IF, ST_SAME, elif_parse, if_eval, 1}, {"elif", sizeof("elif")-1, ST_IF, ST_SAME, elif_parse, if_eval, 1}, {"/if", sizeof("/if")-1, ST_IF | ST_ELSE, ST_POP, endif_parse, skip_eval, 0}, {"each", sizeof("each")-1, ST_ANYWHERE, ST_EACH, each_with_parse, each_eval, 1}, {"/each", sizeof("/each")-1, ST_EACH, ST_POP, end_parse, skip_eval, 0}, {"with", sizeof("each")-1, ST_ANYWHERE, ST_WITH, each_with_parse, with_eval, 1}, {"/with", sizeof("/with")-1, ST_WITH, ST_POP, end_parse, skip_eval, 0}, {"include", sizeof("include")-1, ST_ANYWHERE, ST_SAME, include_parse, skip_eval, 1}, {"linclude", sizeof("linclude")-1, ST_ANYWHERE, ST_SAME, linclude_parse, linclude_eval, 1}, {"def", sizeof("def")-1, ST_ANYWHERE, ST_DEF, def_parse, skip_eval, 1}, {"/def", sizeof("/def")-1, ST_DEF, ST_POP, end_parse, skip_eval, 0}, {"call", sizeof("call")-1, ST_ANYWHERE, ST_SAME, call_parse, call_eval, 1}, {"set", sizeof("set")-1, ST_ANYWHERE, ST_SAME, set_parse, set_eval, 1}, {"loop", sizeof("loop")-1, ST_ANYWHERE, ST_LOOP, loop_parse, loop_eval, 1}, {"/loop", sizeof("/loop")-1, ST_LOOP, ST_POP, end_parse, skip_eval, 1}, {"alt", sizeof("alt")-1, ST_ANYWHERE, ST_ALT, alt_parse, alt_eval, 1}, {"/alt", sizeof("/alt")-1, ST_ALT, ST_POP, end_parse, skip_eval, 1}, {"escape", sizeof("escape")-1, ST_ANYWHERE, ST_ESCAPE, escape_parse, escape_eval, 1}, {"/escape", sizeof("/escape")-1, ST_ESCAPE, ST_POP, end_parse, skip_eval, 1}, {NULL}, }; /* Possible Config.VarEscapeMode values */ typedef struct _escape_modes { char *mode; /* Add space for NUL */ NEOS_ESCAPE context; /* Context of the name */ } CS_ESCAPE_MODES; CS_ESCAPE_MODES EscapeModes[] = { {"none", NEOS_ESCAPE_NONE}, {"html", NEOS_ESCAPE_HTML}, {"js", NEOS_ESCAPE_SCRIPT}, {"url", NEOS_ESCAPE_URL}, {NULL}, }; /* **** CS alloc/dealloc ******************************************** */ static int NodeNumber = 0; static void init_node_pos(CSTREE *node, CSPARSE *parse) { CS_POSITION *pos = &parse->pos; char *data; if (parse->offset < pos->cur_offset) { /* Oops, we went backwards in file, is this an error? */ node->linenum = -1; node->colnum = parse->offset; return; } /* Start counting from 1 not 0 */ if (pos->line == 0) pos->line = 1; if (pos->col == 0) pos->col = 1; if (parse->context == NULL) { /* Not in a file */ node->fname = NULL; } else { node->fname = strdup(parse->context); if (node->fname == NULL) { /* malloc error, cannot proceed */ node->linenum = -1; return; } } data = parse->context_string; if (data == NULL) { node->linenum = -1; return; } while (pos->cur_offset < parse->offset) { if (data[pos->cur_offset] == '\n') { pos->line++; pos->col = 1; } else { pos->col++; } pos->cur_offset++; } node->linenum = pos->line; node->colnum = pos->col; return; } static NEOERR *alloc_node (CSTREE **node, CSPARSE *parse) { CSTREE *my_node; *node = NULL; my_node = (CSTREE *) calloc (1, sizeof (CSTREE)); if (my_node == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for node"); my_node->cmd = 0; my_node->node_num = NodeNumber++; *node = my_node; if (parse->audit_mode) { init_node_pos(my_node, parse); } return STATUS_OK; } /* TODO: make these deallocations linear and not recursive */ static void dealloc_arg (CSARG **arg) { CSARG *p; if (*arg == NULL) return; p = *arg; if (p->expr1) dealloc_arg (&(p->expr1)); if (p->expr2) dealloc_arg (&(p->expr2)); if (p->next) dealloc_arg (&(p->next)); if (p->argexpr) free(p->argexpr); free(p); *arg = NULL; } static void dealloc_node (CSTREE **node) { CSTREE *my_node; if (*node == NULL) return; my_node = *node; if (my_node->case_0) dealloc_node (&(my_node->case_0)); if (my_node->case_1) dealloc_node (&(my_node->case_1)); if (my_node->next) dealloc_node (&(my_node->next)); if (my_node->vargs) dealloc_arg (&(my_node->vargs)); if (my_node->arg1.expr1) dealloc_arg (&(my_node->arg1.expr1)); if (my_node->arg1.expr2) dealloc_arg (&(my_node->arg1.expr2)); if (my_node->arg1.next) dealloc_arg (&(my_node->arg1.next)); if (my_node->arg2.expr1) dealloc_arg (&(my_node->arg2.expr1)); if (my_node->arg2.expr2) dealloc_arg (&(my_node->arg2.expr2)); if (my_node->arg2.next) dealloc_arg (&(my_node->arg2.next)); if (my_node->arg1.argexpr) free(my_node->arg1.argexpr); if (my_node->arg2.argexpr) free(my_node->arg2.argexpr); if (my_node->fname) free(my_node->fname); free(my_node); *node = NULL; } static void dealloc_macro (CS_MACRO **macro) { CS_MACRO *my_macro; if (*macro == NULL) return; my_macro = *macro; if (my_macro->name) free (my_macro->name); if (my_macro->args) dealloc_arg (&(my_macro->args)); if (my_macro->next) dealloc_macro (&(my_macro->next)); free (my_macro); *macro = NULL; } static void dealloc_function (CS_FUNCTION **csf) { CS_FUNCTION *my_csf; if (*csf == NULL) return; my_csf = *csf; if (my_csf->name) free (my_csf->name); if (my_csf->next) dealloc_function (&(my_csf->next)); free (my_csf); *csf = NULL; } static int find_open_delim (CSPARSE *parse, char *buf, int x, int len) { char *p; int ws_index = 2+parse->taglen; while (x < len) { p = strchr (&(buf[x]), '<'); if (p == NULL) return -1; if (p[1] == '?' && !strncasecmp(&p[2], parse->tag, parse->taglen) && (p[ws_index] == ' ' || p[ws_index] == '\n' || p[ws_index] == '\t' || p[ws_index] == '\r')) /* if (p[1] && p[1] == '?' && p[2] && (p[2] == 'C' || p[2] == 'c') && p[3] && (p[3] == 'S' || p[3] == 's') && p[4] && (p[4] == ' ' || p[4] == '\n' || p[4] == '\t' || p[4] == '\r')) */ { return p - buf; } x = p - buf + 1; } return -1; } static NEOERR *_store_error (CSPARSE *parse, NEOERR *err) { CS_ERROR *ptr; CS_ERROR *node; node = (CS_ERROR *) calloc(1, sizeof(CS_ERROR)); if (node == NULL) { return nerr_raise (NERR_NOMEM, "Unable to allocate memory for error entry"); } node->err = err; if (parse->err_list == NULL) { parse->err_list = node; return STATUS_OK; } ptr = parse->err_list; while (ptr->next != NULL) ptr = ptr->next; ptr->next = node; return STATUS_OK; } NEOERR *cs_parse_file (CSPARSE *parse, const char *path) { NEOERR *err; char *ibuf; const char *save_context; int save_infile; char fpath[_POSIX_PATH_MAX]; CS_POSITION pos; if (path == NULL) return nerr_raise (NERR_ASSERT, "path is NULL"); if (parse->fileload) { err = parse->fileload(parse->fileload_ctx, parse->hdf, path, &ibuf); } else { if (path[0] != '/') { err = hdf_search_path (parse->hdf, path, fpath); if (parse->global_hdf && nerr_handle(&err, NERR_NOT_FOUND)) err = hdf_search_path(parse->global_hdf, path, fpath); if (err != STATUS_OK) return nerr_pass(err); path = fpath; } err = ne_load_file (path, &ibuf); } if (err) return nerr_pass (err); save_context = parse->context; parse->context = path; save_infile = parse->in_file; parse->in_file = 1; if (parse->audit_mode) { /* Save previous position before parsing the new file */ memcpy(&pos, &parse->pos, sizeof(CS_POSITION)); parse->pos.line = 0; parse->pos.col = 0; parse->pos.cur_offset = 0; } err = cs_parse_string(parse, ibuf, strlen(ibuf)); if (parse->audit_mode) { memcpy(&parse->pos, &pos, sizeof(CS_POSITION)); } parse->in_file = save_infile; parse->context = save_context; return nerr_pass(err); } static char *find_context (CSPARSE *parse, int offset, char *buf, size_t blen) { FILE *fp; int dump_err = 1; char line[256]; int count = 0; int lineno = 0; char *data; if (offset == -1) offset = parse->offset; do { if (parse->in_file && parse->context) { /* Open the file and find which line we're on */ fp = fopen(parse->context, "r"); if (fp == NULL) { ne_warn("Unable to open context %s", parse->context); break; } while (fgets(line, sizeof(line), fp) != NULL) { count += strlen(line); if (strchr(line, '\n') != NULL) lineno++; if (count > offset) break; } fclose (fp); snprintf (buf, blen, "[%s:%d]", parse->context, lineno); } else { data = parse->context_string; if (data != NULL) { lineno = 1; while (count < offset) { if (data[count++] == '\n') lineno++; } if (parse->context) snprintf (buf, blen, "[%s:~%d]", parse->context, lineno); else snprintf (buf, blen, "[lineno:~%d]", lineno); } else { if (parse->context) snprintf (buf, blen, "[%s:%d]", parse->context, offset); else snprintf (buf, blen, "[offset:%d]", offset); } } dump_err = 0; } while (0); if (dump_err) { if (parse->context) snprintf (buf, blen, "[-E- %s:%d]", parse->context, offset); else snprintf (buf, blen, "[-E- offset:%d]", offset); } return buf; } static char *expand_state (CS_STATE state) { static char buf[256]; if (state & ST_GLOBAL) return "GLOBAL"; else if (state & ST_IF) return "IF"; else if (state & ST_ELSE) return "ELSE"; else if (state & ST_EACH) return "EACH"; else if (state & ST_WITH) return "WITH"; else if (state & ST_DEF) return "DEF"; else if (state & ST_LOOP) return "LOOP"; else if (state & ST_ALT) return "ALT"; else if (state & ST_ESCAPE) return "ESCAPE"; snprintf(buf, sizeof(buf), "Unknown state %d", state); return buf; } NEOERR *cs_parse_string (CSPARSE *parse, char *ibuf, size_t ibuf_len) { NEOERR *err = STATUS_OK; STACK_ENTRY *entry, *current_entry; char *p; char *token; int done = 0; int i, n; char *arg; int initial_stack_depth; int initial_offset; char *initial_context; char tmp[256]; err = uListAppend(parse->alloc, ibuf); if (err) { free (ibuf); return nerr_pass (err); } initial_stack_depth = uListLength(parse->stack); initial_offset = parse->offset; initial_context = parse->context_string; parse->offset = 0; parse->context_string = ibuf; while (!done) { /* Stage 1: Find offset, ibuf_len); if (i >= 0) { ibuf[i] = '\0'; /* Create literal with data up until start delim */ /* ne_warn ("literal -> %d-%d", parse->offset, i); */ err = (*(Commands[0].parse_handler))(parse, 0, &(ibuf[parse->offset])); /* skip delim */ token = &(ibuf[i+3+parse->taglen]); while (*token && isspace(*token)) token++; p = strstr (token, "?>"); if (p == NULL) { return nerr_raise (NERR_PARSE, "%s Missing end ?> at %s", find_context(parse, i, tmp, sizeof(tmp)), &(ibuf[parse->offset])); } *p = '\0'; if (strstr (token, " at %s", find_context(parse, i, tmp, sizeof(tmp)), token); } parse->offset = p - ibuf + 2; if (token[0] != '#') /* handle comments */ { for (i = 1; Commands[i].cmd; i++) { n = Commands[i].cmdlen; if (!strncasecmp(token, Commands[i].cmd, n)) { if ((Commands[i].has_arg && ((token[n] == ':') || (token[n] == '!'))) || (token[n] == ' ' || token[n] == '\0' || token[n] == '\r' || token[n] == '\n')) { err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) goto cs_parse_done; if (!(Commands[i].allowed_state & entry->state)) { return nerr_raise (NERR_PARSE, "%s Command %s not allowed in %s", Commands[i].cmd, find_context(parse, -1, tmp, sizeof(tmp)), expand_state(entry->state)); } if (Commands[i].has_arg) { /* Need to parse out arg */ arg = &token[n]; err = (*(Commands[i].parse_handler))(parse, i, arg); } else { err = (*(Commands[i].parse_handler))(parse, i, NULL); } if (err != STATUS_OK) goto cs_parse_done; if (Commands[i].next_state & ST_POP) { void *ptr; err = uListPop(parse->stack, &ptr); if (err != STATUS_OK) goto cs_parse_done; entry = (STACK_ENTRY *)ptr; if (entry->next_tree) parse->current = entry->next_tree; else parse->current = entry->tree; free(entry); } if ((Commands[i].next_state & ~ST_POP) != ST_SAME) { entry = (STACK_ENTRY *) calloc (1, sizeof (STACK_ENTRY)); if (entry == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for stack entry", find_context(parse, -1, tmp, sizeof(tmp))); entry->state = Commands[i].next_state; entry->tree = parse->current; entry->location = parse->offset; /* Set the new stack escape context to the parent one */ err = uListGet (parse->stack, -1, (void *)¤t_entry); if (err != STATUS_OK) { free (entry); goto cs_parse_done; } entry->escape = current_entry->escape; /* Get the future escape context from parse because when * we parse "escape", the new stack has not yet been established. */ entry->escape = parse->escaping.next_stack; parse->escaping.next_stack = parse->escaping.global_ctx; err = uListAppend(parse->stack, entry); if (err != STATUS_OK) { free (entry); goto cs_parse_done; } } break; } } } if (Commands[i].cmd == NULL) { return nerr_raise (NERR_PARSE, "%s Unknown command %s", find_context(parse, -1, tmp, sizeof(tmp)), token); } } } else { /* Create literal with all remaining data */ err = (*(Commands[0].parse_handler))(parse, 0, &(ibuf[parse->offset])); done = 1; } } /* Should we check the parse stack here? */ while (uListLength(parse->stack) > initial_stack_depth) { err = uListPop(parse->stack, (void *)&entry); if (err != STATUS_OK) goto cs_parse_done; if (entry->state & ~(ST_GLOBAL | ST_POP)) return nerr_raise (NERR_PARSE, "%s Non-terminted %s clause", find_context(parse, entry->location, tmp, sizeof(tmp)), expand_state(entry->state)); } cs_parse_done: parse->offset = initial_offset; parse->context_string = initial_context; parse->escaping.current = NEOS_ESCAPE_NONE; return nerr_pass(err); } static CS_LOCAL_MAP * lookup_map (CSPARSE *parse, char *name, char **rest) { CS_LOCAL_MAP *map; char *c; /* This shouldn't happen, but it did once... */ if (name == NULL) return NULL; map = parse->locals; c = strchr (name, '.'); if (c != NULL) *c = '\0'; *rest = c; while (map != NULL) { if (!strcmp (map->name, name)) { if (c != NULL) *c = '.'; return map; } map = map->next; } if (c != NULL) *c = '.'; return NULL; } static HDF *var_lookup_obj (CSPARSE *parse, char *name) { CS_LOCAL_MAP *map; char *c; HDF *ret_hdf; map = lookup_map (parse, name, &c); if (map && map->type == CS_TYPE_VAR) { if (c == NULL) { return map->h; } else { return hdf_get_obj (map->h, c+1); } } /* smarti: Added support for global hdf under local hdf */ /* return hdf_get_obj (parse->hdf, name); */ ret_hdf = hdf_get_obj (parse->hdf, name); if (ret_hdf == NULL && parse->global_hdf != NULL) { ret_hdf = hdf_get_obj (parse->global_hdf, name); } return ret_hdf; } /* Ugh, I have to write the same walking code because I can't grab the * object for writing, as it might not exist... */ static NEOERR *var_set_value (CSPARSE *parse, char *name, char *value) { CS_LOCAL_MAP *map; char *c; map = parse->locals; c = strchr (name, '.'); if (c != NULL) *c = '\0'; while (map != NULL) { if (!strcmp (map->name, name)) { if (map->type == CS_TYPE_VAR) { if (c == NULL) { if (map->h == NULL) /* node didn't exist yet */ return nerr_pass (hdf_set_value (parse->hdf, map->s, value)); else return nerr_pass (hdf_set_value (map->h, NULL, value)); } else { *c = '.'; if (map->h == NULL) /* node didn't exist yet */ { NEOERR *err; char *mapped_name = sprintf_alloc("%s%s", map->s, c); if (mapped_name == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory to create mapped name"); err = hdf_set_value(parse->hdf, mapped_name, value); free(mapped_name); return nerr_pass(err); } return nerr_pass (hdf_set_value (map->h, c+1, value)); } } else { if (c == NULL) { char *tmp = NULL; /* If this is a string, it might be what we're setting, * ie */ if (map->type == CS_TYPE_STRING && map->map_alloc) tmp = map->s; map->type = CS_TYPE_STRING; map->map_alloc = 1; map->s = strdup(value); if (tmp != NULL) free(tmp); if (map->s == NULL && value != NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory to set var"); return STATUS_OK; } else { ne_warn("WARNING!! Trying to set sub element '%s' of local variable '%s' which doesn't map to an HDF variable, ignoring", c+1, map->name); return STATUS_OK; } } } map = map->next; } if (c != NULL) *c = '.'; return nerr_pass (hdf_set_value (parse->hdf, name, value)); } static char *var_lookup (CSPARSE *parse, char *name) { CS_LOCAL_MAP *map; char *c; char* retval; map = lookup_map (parse, name, &c); if (map) { if (map->type == CS_TYPE_VAR) { if (c == NULL) { return hdf_obj_value (map->h); } else { return hdf_get_value (map->h, c+1, NULL); } } /* Hmm, if c != NULL, they are asking for a sub member of something * which isn't a var... right now we ignore them, I don't know what * the right thing is */ /* hmm, its possible now that they are getting a reference to a * string that will be deleted... where is it used? */ else if (map->type == CS_TYPE_STRING) { return map->s; } else if (map->type == CS_TYPE_NUM) { char buf[40]; if (map->s) return map->s; snprintf (buf, sizeof(buf), "%ld", map->n); map->s = strdup(buf); map->map_alloc = 1; return map->s; } } /* smarti: Added support for global hdf under local hdf */ /* return hdf_get_value (parse->hdf, name, NULL); */ retval = hdf_get_value (parse->hdf, name, NULL); if (retval == NULL && parse->global_hdf != NULL) { retval = hdf_get_value (parse->global_hdf, name, NULL); } return retval; } long int var_int_lookup (CSPARSE *parse, char *name) { char *vs; vs = var_lookup (parse, name); if (vs == NULL) return 0; else return atoi(vs); } typedef struct _token { CSTOKEN_TYPE type; char *value; size_t len; } CSTOKEN; struct _simple_tokens { BOOL two_chars; char *token; CSTOKEN_TYPE type; } SimpleTokens[] = { { TRUE, "<=", CS_OP_LTE }, { TRUE, ">=", CS_OP_GTE }, { TRUE, "==", CS_OP_EQUAL }, { TRUE, "!=", CS_OP_NEQUAL }, { TRUE, "||", CS_OP_OR }, { TRUE, "&&", CS_OP_AND }, { FALSE, "!", CS_OP_NOT }, /* For now, we are still treating this special instead of as an op * If we make this an op, then we'd have to determine how to handle * NUM types without doing something like #"5" */ /* { FALSE, "#", CS_OP_NUM }, */ { FALSE, "?", CS_OP_EXISTS }, { FALSE, "<", CS_OP_LT }, { FALSE, ">", CS_OP_GT }, { FALSE, "+", CS_OP_ADD }, { FALSE, "-", CS_OP_SUB }, { FALSE, "*", CS_OP_MULT }, { FALSE, "/", CS_OP_DIV }, { FALSE, "%", CS_OP_MOD }, { FALSE, "(", CS_OP_LPAREN }, { FALSE, ")", CS_OP_RPAREN }, { FALSE, "[", CS_OP_LBRACKET }, { FALSE, "]", CS_OP_RBRACKET }, { FALSE, ".", CS_OP_DOT }, { FALSE, ",", CS_OP_COMMA }, { FALSE, NULL, 0 } }; #define MAX_TOKENS 256 static NEOERR *parse_tokens (CSPARSE *parse, char *arg, CSTOKEN *tokens, int *used_tokens) { char tmp[256]; int ntokens = 0; int x; BOOL found; BOOL last_is_op = 1; char *p, *p2; char *expr = arg; while (arg && *arg != '\0') { while (*arg && isspace(*arg)) arg++; if (*arg == '\0') break; x = 0; found = FALSE; /* If we already saw an operator, and this is a +/-, assume its * a number */ if (!(last_is_op && (*arg == '+' || *arg == '-'))) { while ((found == FALSE) && SimpleTokens[x].token) { if (((SimpleTokens[x].two_chars == TRUE) && (*arg == SimpleTokens[x].token[0]) && (*(arg + 1) == SimpleTokens[x].token[1])) || ((SimpleTokens[x].two_chars == FALSE) && (*arg == SimpleTokens[x].token[0]))) { tokens[ntokens++].type = SimpleTokens[x].type; found = TRUE; arg++; if (SimpleTokens[x].two_chars) arg++; } x++; } /* Another special case: RPAREN and RBRACKET can have another op * after it */ if (found && !(tokens[ntokens-1].type == CS_OP_RPAREN || tokens[ntokens-1].type == CS_OP_RBRACKET)) last_is_op = 1; } if (found == FALSE) { if (*arg == '#') { /* TODO: make # an operator and not syntax */ arg++; tokens[ntokens].type = CS_TYPE_NUM; tokens[ntokens].value = arg; strtol(arg, &p, 0); if (p == arg) { tokens[ntokens].type = CS_TYPE_VAR_NUM; p = strpbrk(arg, "\"?<>=!#-+|&,)*/%[]( \t\r\n"); if (p == arg) return nerr_raise (NERR_PARSE, "%s Missing varname/number after #: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } if (p == NULL) tokens[ntokens].len = strlen(arg); else tokens[ntokens].len = p - arg; ntokens++; arg = p; } else if (*arg == '"') { arg++; tokens[ntokens].type = CS_TYPE_STRING; tokens[ntokens].value = arg; p = strchr (arg, '"'); if (p == NULL) return nerr_raise (NERR_PARSE, "%s Missing end of string: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); tokens[ntokens].len = p - arg; ntokens++; arg = p + 1; } else if (*arg == '\'') { arg++; tokens[ntokens].type = CS_TYPE_STRING; tokens[ntokens].value = arg; p = strchr (arg, '\''); if (p == NULL) return nerr_raise (NERR_PARSE, "%s Missing end of string: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); tokens[ntokens].len = p - arg; ntokens++; arg = p + 1; } else if (*arg == '$') { /* TODO: make $ an operator and not syntax */ arg++; tokens[ntokens].type = CS_TYPE_VAR; tokens[ntokens].value = arg; p = strpbrk(arg, "\"?<>=!#-+|&,)*/%[]( \t\r\n"); if (p == arg) return nerr_raise (NERR_PARSE, "%s Missing varname after $: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); if (p == NULL) tokens[ntokens].len = strlen(arg); else tokens[ntokens].len = p - arg; ntokens++; arg = p; } else { tokens[ntokens].type = CS_TYPE_VAR; tokens[ntokens].value = arg; /* Special case for Dave: If this is entirely a number, treat it * as one */ strtol(arg, &p2, 0); p = strpbrk(arg, "\"?<>=!#-+|&,)*/%[]( \t\r\n"); /* This is complicated because +/- is valid in a number, but not * in a varname */ if (p2 != arg && (p <= p2 || (p == NULL && *p2 == '\0'))) { tokens[ntokens].type = CS_TYPE_NUM; tokens[ntokens].len = p2 - arg; arg = p2; } else { if (p == arg) return nerr_raise (NERR_PARSE, "%s Var arg specified with no varname: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); if (p == NULL) tokens[ntokens].len = strlen(arg); else tokens[ntokens].len = p - arg; arg = p; } ntokens++; } last_is_op = 0; } if (ntokens >= MAX_TOKENS) return nerr_raise (NERR_PARSE, "%s Expression exceeds maximum number of tokens of %d: %s", find_context(parse, -1, tmp, sizeof(tmp)), MAX_TOKENS, expr); } *used_tokens = ntokens; return STATUS_OK; } CSTOKEN_TYPE OperatorOrder[] = { CS_OP_COMMA, CS_OP_OR, CS_OP_AND, CS_OP_EQUAL | CS_OP_NEQUAL, CS_OP_GT | CS_OP_GTE | CS_OP_LT | CS_OP_LTE, CS_OP_ADD | CS_OP_SUB, CS_OP_MULT | CS_OP_DIV | CS_OP_MOD, CS_OP_NOT | CS_OP_EXISTS, CS_OP_LBRACKET | CS_OP_DOT | CS_OP_LPAREN, 0 }; static char *expand_token_type(CSTOKEN_TYPE t_type, int more) { switch (t_type) { case CS_OP_EXISTS: return "?"; case CS_OP_NOT: return "!"; case CS_OP_NUM: return "#"; case CS_OP_EQUAL: return "=="; case CS_OP_NEQUAL: return "!="; case CS_OP_LT: return "<"; case CS_OP_LTE: return "<="; case CS_OP_GT: return ">"; case CS_OP_GTE: return ">="; case CS_OP_AND: return "&&"; case CS_OP_OR: return "||"; case CS_OP_ADD: return "+"; case CS_OP_SUB: return "-"; case CS_OP_MULT: return "*"; case CS_OP_DIV: return "/"; case CS_OP_MOD: return "%"; case CS_OP_LPAREN: return "("; case CS_OP_RPAREN: return ")"; case CS_OP_LBRACKET: return "["; case CS_OP_RBRACKET: return "]"; case CS_OP_DOT : return "."; case CS_OP_COMMA : return ","; case CS_TYPE_STRING: return more ? "STRING" : "s"; case CS_TYPE_NUM: return more ? "NUM" : "n"; case CS_TYPE_VAR: return more ? "VAR" : "v"; case CS_TYPE_VAR_NUM: return more ? "VARNUM" : "vn"; case CS_TYPE_MACRO: return more ? "MACRO" : "m"; case CS_TYPE_FUNCTION: return more ? "FUNC" : "f"; default: return "u"; } return "u"; } static char *token_list (CSTOKEN *tokens, int ntokens, char *buf, size_t buflen) { char *p = buf; int i, t; char save; for (i = 0; i < ntokens && buflen > 0; i++) { if (tokens[i].value) { save = tokens[i].value[tokens[i].len]; tokens[i].value[tokens[i].len] = '\0'; t = snprintf(p, buflen, "%s%d:%s:'%s'", i ? " ":"", i, expand_token_type(tokens[i].type, 0), tokens[i].value); tokens[i].value[tokens[i].len] = save; } else { t = snprintf(p, buflen, "%s%d:%s", i ? " ":"", i, expand_token_type(tokens[i].type, 0)); } if (t == -1 || t >= buflen) return buf; buflen -= t; p += t; } return buf; } static NEOERR *parse_expr2 (CSPARSE *parse, CSTOKEN *tokens, int ntokens, int lvalue, CSARG *arg) { NEOERR *err = STATUS_OK; char tmp[256]; char tmp2[256]; int x, op; int m; #if DEBUG_EXPR_PARSE fprintf(stderr, "%s\n", token_list(tokens, ntokens, tmp, sizeof(tmp))); for (x = 0; x < ntokens; x++) { fprintf (stderr, "%s ", expand_token_type(tokens[x].type, 0)); } fprintf(stderr, "\n"); #endif /* Not quite sure what to do with this case... */ if (ntokens == 0) { return nerr_raise (NERR_PARSE, "%s Bad Expression", find_context(parse, -1, tmp, sizeof(tmp))); } if (ntokens == 1) { x = 0; if (tokens[0].type & CS_TYPES) { arg->s = tokens[0].value; if (tokens[0].len >= 0) arg->s[tokens[0].len] = '\0'; arg->op_type = tokens[0].type; if (tokens[x].type == CS_TYPE_NUM) arg->n = strtol(arg->s, NULL, 0); return STATUS_OK; } else { return nerr_raise (NERR_PARSE, "%s Terminal token is not an argument, type is %s", find_context(parse, -1, tmp, sizeof(tmp)), expand_token_type(tokens[0].type, 0)); } } /* if (ntokens == 2 && (tokens[0].type & CS_OPS_UNARY)) { arg->op_type = tokens[0].type; arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); err = parse_expr2(parse, tokens + 1, 1, lvalue, arg->expr1); return nerr_pass(err); } */ op = 0; while (OperatorOrder[op]) { x = ntokens-1; while (x >= 0) { /* handle associative ops by skipping through the entire set here, * ie the whole thing is an expression that can't match a binary op */ if (tokens[x].type & CS_OP_RPAREN) { m = 1; x--; while (x >= 0) { if (tokens[x].type & CS_OP_RPAREN) m++; if (tokens[x].type & CS_OP_LPAREN) m--; if (m == 0) break; x--; } if (m) return nerr_raise (NERR_PARSE, "%s Missing left parenthesis in expression", find_context(parse, -1, tmp, sizeof(tmp))); /* if (x == 0) break; */ /* x--; */ /* we don't do an x-- here, because we are special casing the * left bracket to be both an operator and an associative */ } if (tokens[x].type & CS_OP_RBRACKET) { m = 1; x--; while (x >= 0) { if (tokens[x].type & CS_OP_RBRACKET) m++; if (tokens[x].type & CS_OP_LBRACKET) m--; if (m == 0) break; x--; } if (m) return nerr_raise (NERR_PARSE, "%s Missing left bracket in expression", find_context(parse, -1, tmp, sizeof(tmp))); if (x == 0) break; /* we don't do an x-- here, because we are special casing the * left bracket to be both an operator and an associative */ } if (lvalue && !(tokens[x].type & CS_OPS_LVALUE)) { return nerr_raise (NERR_PARSE, "%s Invalid op '%s' in lvalue", find_context(parse, -1, tmp, sizeof(tmp)), expand_token_type(tokens[x].type, 0)); } if (tokens[x].type & OperatorOrder[op]) { if (tokens[x].type & CS_OPS_UNARY) { if (x == 0) { arg->op_type = tokens[x].type; arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); if (tokens[x].type & CS_OP_LPAREN) { if (!(tokens[ntokens-1].type & CS_OP_RPAREN)) { return nerr_raise (NERR_PARSE, "%s Missing right parenthesis in expression", find_context(parse, -1, tmp, sizeof(tmp))); } /* XXX: we might want to set lvalue to 0 here */ /* -2 since we strip the RPAREN as well */ err = parse_expr2(parse, tokens + 1, ntokens-2, lvalue, arg->expr1); } else { err = parse_expr2(parse, tokens + 1, ntokens-1, lvalue, arg->expr1); } return nerr_pass(err); } } else if (tokens[x].type == CS_OP_COMMA) { /* Technically, comma should be a left to right, not right to * left, so we're going to build up the arguments in reverse * order... */ arg->op_type = tokens[x].type; /* The actual argument is expr1 */ arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); /* The previous argument is next */ arg->next = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL || arg->next == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); err = parse_expr2(parse, tokens + x + 1, ntokens-x-1, lvalue, arg->expr1); if (err) return nerr_pass (err); err = parse_expr2(parse, tokens, x, lvalue, arg->next); if (err) return nerr_pass (err); return STATUS_OK; } else { arg->op_type = tokens[x].type; arg->expr2 = (CSARG *) calloc (1, sizeof (CSARG)); arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL || arg->expr2 == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); if (tokens[x].type & CS_OP_LBRACKET) { if (!(tokens[ntokens-1].type & CS_OP_RBRACKET)) { return nerr_raise (NERR_PARSE, "%s Missing right bracket in expression", find_context(parse, -1, tmp, sizeof(tmp))); } /* Inside of brackets, we don't limit to valid lvalue ops */ /* -2 since we strip the RBRACKET as well */ err = parse_expr2(parse, tokens + x + 1, ntokens-x-2, 0, arg->expr2); } else { err = parse_expr2(parse, tokens + x + 1, ntokens-x-1, lvalue, arg->expr2); } if (err) return nerr_pass (err); err = parse_expr2(parse, tokens, x, lvalue, arg->expr1); if (err) return nerr_pass (err); return STATUS_OK; } } x--; } op++; } /* Unary op against an entire expression */ if ((tokens[0].type & CS_OPS_UNARY) && tokens[1].type == CS_OP_LPAREN && tokens[ntokens-1].type == CS_OP_RPAREN) { arg->op_type = tokens[0].type; arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); err = parse_expr2(parse, tokens + 2, ntokens-3, lvalue, arg->expr1); return nerr_pass(err); } if (tokens[0].type & CS_OPS_UNARY) { arg->op_type = tokens[0].type; arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); err = parse_expr2(parse, tokens + 1, ntokens-1, lvalue, arg->expr1); return nerr_pass(err); } /* function call */ if ((tokens[0].type & CS_TYPE_VAR) && tokens[1].type == CS_OP_LPAREN && tokens[ntokens-1].type == CS_OP_RPAREN) { CS_FUNCTION *csf; int nargs; if (tokens[0].len >= 0) tokens[0].value[tokens[0].len] = '\0'; arg->op_type = CS_TYPE_FUNCTION; csf = parse->functions; while (csf != NULL) { if (!strcmp(tokens[0].value, csf->name)) { arg->function = csf; break; } csf = csf->next; } if (csf == NULL) { return nerr_raise (NERR_PARSE, "%s Unknown function %s called", find_context(parse, -1, tmp, sizeof(tmp)), tokens[0].value); } arg->expr1 = (CSARG *) calloc (1, sizeof (CSARG)); if (arg->expr1 == NULL) return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for expression", find_context(parse, -1, tmp, sizeof(tmp))); if (ntokens-3 > 0) { err = parse_expr2(parse, tokens + 2, ntokens-3, lvalue, arg->expr1); if (err) return nerr_pass(err); } else { free(arg->expr1); arg->expr1 = NULL; } nargs = rearrange_for_call(&(arg->expr1)); if (nargs != arg->function->n_args) { return nerr_raise (NERR_PARSE, "%s Incorrect number of arguments in call to %s, expected %d, got %d", find_context(parse, -1, tmp, sizeof(tmp)), tokens[0].value, arg->function->n_args, nargs); } return nerr_pass(err); } return nerr_raise (NERR_PARSE, "%s Bad Expression:%s", find_context(parse, -1, tmp, sizeof(tmp)), token_list(tokens, ntokens, tmp2, sizeof(tmp2))); } static NEOERR *parse_expr (CSPARSE *parse, char *arg, int lvalue, CSARG *expr) { NEOERR *err; CSTOKEN tokens[MAX_TOKENS]; int ntokens = 0; memset(tokens, 0, sizeof(CSTOKEN) * MAX_TOKENS); err = parse_tokens (parse, arg, tokens, &ntokens); if (err) return nerr_pass(err); if (parse->audit_mode) { /* Save the complete expression string for future reference */ expr->argexpr = strdup(arg); } err = parse_expr2 (parse, tokens, ntokens, lvalue, expr); if (err) return nerr_pass(err); return STATUS_OK; } static NEOERR *literal_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; /* ne_warn ("literal: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; node->arg1.op_type = CS_TYPE_STRING; node->arg1.s = arg; *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *literal_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; if (node->arg1.s != NULL) err = parse->output_cb (parse->output_ctx, node->arg1.s); *next = node->next; return nerr_pass(err); } static NEOERR *name_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; char *a, *s; char tmp[256]; /* ne_warn ("name: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ a = neos_strip(arg); s = strpbrk(a, "#\" <>"); if (s != NULL) { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Invalid character in var name %s: %c", find_context(parse, -1, tmp, sizeof(tmp)), a, s[0]); } node->arg1.op_type = CS_TYPE_VAR; node->arg1.s = a; *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *escape_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; char *a = NULL; char tmp[256]; CS_ESCAPE_MODES *esc_cursor; CSTREE *node; /* ne_warn ("escape: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; /* Since this throws an error always if there's a problem * this flag seems pointless, but following convention, * here it is. */ if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* ignore colon, space, etc */ /* Parse the arg - we're expecting a string */ err = parse_expr (parse, arg, 0, &(node->arg1)); if (err) { dealloc_node(&node); return nerr_pass(err); } if (node->arg1.op_type != CS_TYPE_STRING) { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Invalid argument for escape: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } a = neos_strip(node->arg1.s); /* Strip spaces for testing */ /* Ensure the mode specified is allowed */ for (esc_cursor = &EscapeModes[0]; esc_cursor->mode != NULL; esc_cursor++) if (!strncasecmp(a, esc_cursor->mode, strlen(esc_cursor->mode))) { if (err != STATUS_OK) return nerr_pass(err); parse->escaping.next_stack = esc_cursor->context; break; } /* Didn't find an acceptable value we were looking for */ if (esc_cursor->mode == NULL) { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Invalid argument for escape: %s", find_context(parse, -1, tmp, sizeof(tmp)), a); } *(parse->next) = node; parse->next = &(node->case_0); parse->current = node; return STATUS_OK; } static NEOERR *name_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; HDF *obj; char *v; if (node->arg1.op_type == CS_TYPE_VAR && node->arg1.s != NULL) { obj = var_lookup_obj (parse, node->arg1.s); if (obj != NULL) { v = hdf_obj_name(obj); err = parse->output_cb (parse->output_ctx, v); } } *next = node->next; return nerr_pass(err); } static NEOERR *var_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; STACK_ENTRY *entry; err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) return nerr_pass(err); /* ne_warn ("var: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; /* Default escape the variable based on * current stack's escape context except for * uvar: */ if (!strcmp(Commands[cmd].cmd, "uvar")) node->escape = NEOS_ESCAPE_NONE; else node->escape = entry->escape; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ err = parse_expr (parse, arg, 0, &(node->arg1)); if (err) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *lvar_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; /* ne_warn ("lvar: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ err = parse_expr (parse, arg, 0, &(node->arg1)); if (err) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *linclude_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; /* ne_warn ("linclude: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ err = parse_expr (parse, arg, 0, &(node->arg1)); if (err) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *alt_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; /* ne_warn ("var: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ err = parse_expr (parse, arg, 0, &(node->arg1)); if (err) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->case_0); parse->current = node; return STATUS_OK; } static NEOERR *evar_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; char *a, *s; const char *save_context; int save_infile; char tmp[256]; /* ne_warn ("evar: %s", arg); */ err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ a = neos_strip(arg); s = strpbrk(a, "#\" <>"); if (s != NULL) { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Invalid character in var name %s: %c", find_context(parse, -1, tmp, sizeof(tmp)), a, s[0]); } err = hdf_get_copy (parse->hdf, a, &s, NULL); if (err) { dealloc_node(&node); return nerr_pass (err); } if (node->flags & CSF_REQUIRED && s == NULL) { dealloc_node(&node); return nerr_raise (NERR_NOT_FOUND, "%s Unable to evar empty variable %s", find_context(parse, -1, tmp, sizeof(tmp)), a); } node->arg1.op_type = CS_TYPE_VAR; node->arg1.s = a; *(parse->next) = node; parse->next = &(node->next); parse->current = node; save_context = parse->context; save_infile = parse->in_file; parse->context = a; parse->in_file = 0; if (s) err = cs_parse_string (parse, s, strlen(s)); parse->context = save_context; parse->in_file = save_infile; return nerr_pass (err); } static NEOERR *if_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; /* ne_warn ("if: %s", arg); */ err = alloc_node (&node, parse); if (err != STATUS_OK) return nerr_pass(err); node->cmd = cmd; arg++; err = parse_expr (parse, arg, 0, &(node->arg1)); if (err != STATUS_OK) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->case_0); parse->current = node; return STATUS_OK; } char *arg_eval (CSPARSE *parse, CSARG *arg) { switch ((arg->op_type & CS_TYPES)) { case CS_TYPE_STRING: return arg->s; case CS_TYPE_VAR: return var_lookup (parse, arg->s); case CS_TYPE_NUM: case CS_TYPE_VAR_NUM: default: ne_warn ("Unsupported type %s in arg_eval", expand_token_type(arg->op_type, 1)); return NULL; } } /* This coerces everything to numbers */ long int arg_eval_num (CSPARSE *parse, CSARG *arg) { long int v = 0; switch ((arg->op_type & CS_TYPES)) { case CS_TYPE_STRING: v = strtol(arg->s, NULL, 0); break; case CS_TYPE_NUM: v = arg->n; break; case CS_TYPE_VAR: case CS_TYPE_VAR_NUM: v = var_int_lookup (parse, arg->s); break; default: ne_warn ("Unsupported type %s in arg_eval_num", expand_token_type(arg->op_type, 1)); v = 0; break; } return v; } /* This is different from arg_eval_num because we don't force strings to * numbers, a string is either a number (if it is all numeric) or we're * testing existance. At least, that's what perl does and what dave * wants */ long int arg_eval_bool (CSPARSE *parse, CSARG *arg) { long int v = 0; char *s, *r; switch ((arg->op_type & CS_TYPES)) { case CS_TYPE_STRING: case CS_TYPE_VAR: if (arg->op_type == CS_TYPE_VAR) s = var_lookup(parse, arg->s); else s = arg->s; if (!s || *s == '\0') return 0; /* non existance or empty is false(0) */ v = strtol(s, &r, 0); if (*r == '\0') /* entire string converted, treat as number */ return v; /* if the entire string didn't convert, then its non-numeric and * exists, so its true (1) */ return 1; case CS_TYPE_NUM: return arg->n; case CS_TYPE_VAR_NUM: /* this implies forced numeric evaluation */ return var_int_lookup (parse, arg->s); break; default: ne_warn ("Unsupported type %s in arg_eval_bool", expand_token_type(arg->op_type, 1)); v = 0; break; } return v; } char *arg_eval_str_alloc (CSPARSE *parse, CSARG *arg) { char *s = NULL; char buf[256]; long int n_val; switch ((arg->op_type & CS_TYPES)) { case CS_TYPE_STRING: s = arg->s; break; case CS_TYPE_VAR: s = var_lookup (parse, arg->s); break; case CS_TYPE_NUM: case CS_TYPE_VAR_NUM: s = buf; n_val = arg_eval_num (parse, arg); snprintf (buf, sizeof(buf), "%ld", n_val); break; default: ne_warn ("Unsupported type %s in arg_eval_str_alloc", expand_token_type(arg->op_type, 1)); s = NULL; break; } if (s) return strdup(s); return NULL; } #if DEBUG_EXPR_EVAL static void expand_arg (CSPARSE *parse, int depth, char *where, CSARG *arg) { int x; for (x=0; xop_type, 0), arg->alloc); if (arg->op_type & CS_OP_NOT) fprintf(stderr, "!"); if (arg->op_type & CS_OP_NUM) fprintf(stderr, "#"); if (arg->op_type & CS_OP_EXISTS) fprintf(stderr, "?"); if (arg->op_type & (CS_TYPE_VAR_NUM | CS_TYPE_NUM)) fprintf(stderr, "#"); if (arg->op_type & CS_TYPE_NUM) fprintf(stderr, "%ld\n", arg->n); else if (arg->op_type & CS_TYPE_STRING) fprintf(stderr, "'%s'\n", arg->s); else if (arg->op_type & CS_TYPE_VAR) fprintf(stderr, "%s = %s\n", arg->s, var_lookup(parse, arg->s)); else if (arg->op_type & CS_TYPE_VAR_NUM) fprintf(stderr, "%s = %ld\n", arg->s, var_int_lookup(parse, arg->s)); else fprintf(stderr, "\n"); } #endif static NEOERR *eval_expr_string(CSPARSE *parse, CSARG *arg1, CSARG *arg2, CSTOKEN_TYPE op, CSARG *result) { char *s1, *s2; int out; result->op_type = CS_TYPE_NUM; s1 = arg_eval (parse, arg1); s2 = arg_eval (parse, arg2); if ((s1 == NULL) || (s2 == NULL)) { switch (op) { case CS_OP_EQUAL: result->n = (s1 == s2) ? 1 : 0; break; case CS_OP_NEQUAL: result->n = (s1 != s2) ? 1 : 0; break; case CS_OP_LT: result->n = ((s1 == NULL) && (s2 != NULL)) ? 1 : 0; break; case CS_OP_LTE: result->n = (s1 == NULL) ? 1 : 0; break; case CS_OP_GT: result->n = ((s1 != NULL) && (s2 == NULL)) ? 1 : 0; break; case CS_OP_GTE: result->n = (s2 == NULL) ? 1 : 0; break; case CS_OP_ADD: /* be sure to transfer ownership of the string here */ result->op_type = CS_TYPE_STRING; if (s1 == NULL) { result->s = s2; result->alloc = arg2->alloc; arg2->alloc = 0; } else { result->s = s1; result->alloc = arg1->alloc; arg1->alloc = 0; } break; default: ne_warn ("Unsupported op %s in eval_expr", expand_token_type(op, 1)); break; } } else { out = strcmp (s1, s2); switch (op) { case CS_OP_EQUAL: result->n = (!out) ? 1 : 0; break; case CS_OP_NEQUAL: result->n = (out) ? 1 : 0; break; case CS_OP_LT: result->n = (out < 0) ? 1 : 0; break; case CS_OP_LTE: result->n = (out <= 0) ? 1 : 0; break; case CS_OP_GT: result->n = (out > 0) ? 1 : 0; break; case CS_OP_GTE: result->n = (out >= 0) ? 1 : 0; break; case CS_OP_ADD: result->op_type = CS_TYPE_STRING; result->alloc = 1; result->s = (char *) calloc ((strlen(s1) + strlen(s2) + 1), sizeof(char)); if (result->s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to concatenate strings in expression: %s + %s", s1, s2); strcpy(result->s, s1); strcat(result->s, s2); break; default: ne_warn ("Unsupported op %s in eval_expr_string", expand_token_type(op, 1)); break; } } return STATUS_OK; } static NEOERR *eval_expr_num(CSPARSE *parse, CSARG *arg1, CSARG *arg2, CSTOKEN_TYPE op, CSARG *result) { long int n1, n2; result->op_type = CS_TYPE_NUM; n1 = arg_eval_num (parse, arg1); n2 = arg_eval_num (parse, arg2); switch (op) { case CS_OP_EQUAL: result->n = (n1 == n2) ? 1 : 0; break; case CS_OP_NEQUAL: result->n = (n1 != n2) ? 1 : 0; break; case CS_OP_LT: result->n = (n1 < n2) ? 1 : 0; break; case CS_OP_LTE: result->n = (n1 <= n2) ? 1 : 0; break; case CS_OP_GT: result->n = (n1 > n2) ? 1 : 0; break; case CS_OP_GTE: result->n = (n1 >= n2) ? 1 : 0; break; case CS_OP_ADD: result->n = (n1 + n2); break; case CS_OP_SUB: result->n = (n1 - n2); break; case CS_OP_MULT: result->n = (n1 * n2); break; case CS_OP_DIV: if (n2 == 0) result->n = UINT_MAX; else result->n = (n1 / n2); break; case CS_OP_MOD: if (n2 == 0) result->n = 0; else result->n = (n1 % n2); break; default: ne_warn ("Unsupported op %s in eval_expr_num", expand_token_type(op, 1)); break; } return STATUS_OK; } static NEOERR *eval_expr_bool(CSPARSE *parse, CSARG *arg1, CSARG *arg2, CSTOKEN_TYPE op, CSARG *result) { long int n1, n2; result->op_type = CS_TYPE_NUM; n1 = arg_eval_bool (parse, arg1); n2 = arg_eval_bool (parse, arg2); switch (op) { case CS_OP_AND: result->n = (n1 && n2) ? 1 : 0; break; case CS_OP_OR: result->n = (n1 || n2) ? 1 : 0; break; default: ne_warn ("Unsupported op %s in eval_expr_bool", expand_token_type(op, 1)); break; } return STATUS_OK; } #if DEBUG_EXPR_EVAL static int _depth = 0; #endif static NEOERR *eval_expr (CSPARSE *parse, CSARG *expr, CSARG *result) { NEOERR *err; if (expr == NULL) return nerr_raise (NERR_ASSERT, "expr is NULL"); if (result == NULL) return nerr_raise (NERR_ASSERT, "result is NULL"); #if DEBUG_EXPR_EVAL _depth++; expand_arg(parse, _depth, "expr", expr); #endif memset(result, 0, sizeof(CSARG)); if (expr->op_type & CS_TYPES) { *result = *expr; /* we transfer ownership of the string here.. ugh */ if (expr->alloc) expr->alloc = 0; #if DEBUG_EXPR_EVAL expand_arg(parse, _depth, "result", result); _depth--; #endif return STATUS_OK; } if (expr->op_type & CS_OP_LPAREN) { /* lparen is a no-op, just skip */ return nerr_pass(eval_expr(parse, expr->expr1, result)); } if (expr->op_type & CS_TYPE_FUNCTION) { if (expr->function == NULL || expr->function->function == NULL) return nerr_raise(NERR_ASSERT, "Function is NULL in attempt to evaluate function call %s", (expr->function) ? expr->function->name : ""); /* The function evaluates all the arguments, so don't pre-evaluate * argument1 */ err = expr->function->function(parse, expr->function, expr->expr1, result); if (err) return nerr_pass(err); /* Indicate whether or not an explicit escape call was made by * setting the mode (usually NONE or FUNCTION). This is ORed to * ensure that escaping calls within other functions do not get * double-escaped. E.g. slice(html_escape(foo), 10, 20) */ parse->escaping.current |= expr->function->escape; } else { CSARG arg1, arg2; arg1.alloc = 0; arg2.alloc = 0; err = eval_expr (parse, expr->expr1, &arg1); if (err) return nerr_pass(err); #if DEBUG_EXPR_EVAL expand_arg(parse, _depth, "arg1", &arg1); #endif if (expr->op_type & CS_OPS_UNARY) { result->op_type = CS_TYPE_NUM; switch (expr->op_type) { case CS_OP_NOT: result->n = arg_eval_bool(parse, &arg1) ? 0 : 1; break; case CS_OP_EXISTS: if (arg1.op_type & (CS_TYPE_VAR | CS_TYPE_VAR_NUM)) { if (arg_eval(parse, &arg1) == NULL) result->n = 0; else result->n = 1; } else { /* All numbers/strings exist */ result->n = 1; } break; case CS_OP_NUM: result->n = arg_eval_num (parse, &arg1); break; case CS_OP_LPAREN: return nerr_raise(NERR_ASSERT, "LPAREN should be handled above"); default: result->n = 0; ne_warn ("Unsupported op %s in eval_expr", expand_token_type(expr->op_type, 1)); break; } } else if (expr->op_type == CS_OP_COMMA) { /* The comma operator, like in C, we return the value of the right * most argument, in this case that's expr1, but we still need to * evaluate the other stuff */ if (expr->next) { err = eval_expr (parse, expr->next, &arg2); #if DEBUG_EXPR_EVAL expand_arg(parse, _depth, "arg2", &arg2); #endif if (err) return nerr_pass(err); if (arg2.alloc) free(arg2.s); } *result = arg1; /* we transfer ownership of the string here.. ugh */ if (arg1.alloc) arg1.alloc = 0; #if DEBUG_EXPR_EVAL expand_arg(parse, _depth, "result", result); _depth--; #endif return STATUS_OK; } else { err = eval_expr (parse, expr->expr2, &arg2); #if DEBUG_EXPR_EVAL expand_arg(parse, _depth, "arg2", &arg2); #endif if (err) return nerr_pass(err); if (expr->op_type == CS_OP_LBRACKET) { /* the bracket op is essentially hdf array lookups, which just * means appending the value of arg2, .0 */ result->op_type = CS_TYPE_VAR; result->alloc = 1; if (arg2.op_type & (CS_TYPE_VAR_NUM | CS_TYPE_NUM)) { long int n2 = arg_eval_num (parse, &arg2); result->s = sprintf_alloc("%s.%ld", arg1.s, n2); if (result->s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to concatenate varnames in expression: %s + %ld", arg1.s, n2); } else { char *s2 = arg_eval (parse, &arg2); if (s2 && s2[0]) { result->s = sprintf_alloc("%s.%s", arg1.s, s2); if (result->s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to concatenate varnames in expression: %s + %s", arg1.s, s2); } else { /* if s2 doesn't match anything, then the whole thing is empty */ result->s = ""; result->alloc = 0; } } } else if (expr->op_type == CS_OP_DOT) { /* the dot op is essentially extending the hdf name, which just * means appending the string .0 */ result->op_type = CS_TYPE_VAR; result->alloc = 1; if (arg2.op_type & CS_TYPES_VAR) { result->s = sprintf_alloc("%s.%s", arg1.s, arg2.s); if (result->s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to concatenate varnames in expression: %s + %s", arg1.s, arg2.s); } else { if (arg2.op_type & CS_TYPE_NUM) { long int n2 = arg_eval_num (parse, &arg2); result->s = sprintf_alloc("%s.%ld", arg1.s, n2); if (result->s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to concatenate varnames in expression: %s + %ld", arg1.s, n2); } else { char *s2 = arg_eval (parse, &arg2); if (s2 && s2[0]) { result->s = sprintf_alloc("%s.%s", arg1.s, s2); if (result->s == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to concatenate varnames in expression: %s + %s", arg1.s, s2); } else { /* if s2 doesn't match anything, then the whole thing is empty */ result->s = ""; result->alloc = 0; } } } } else if (expr->op_type & (CS_OP_AND | CS_OP_OR)) { /* eval as bool */ err = eval_expr_bool (parse, &arg1, &arg2, expr->op_type, result); } else if ((arg1.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) || (arg2.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) || (expr->op_type & (CS_OP_AND | CS_OP_OR | CS_OP_SUB | CS_OP_MULT | CS_OP_DIV | CS_OP_MOD | CS_OP_GT | CS_OP_GTE | CS_OP_LT | CS_OP_LTE))) { /* eval as num */ err = eval_expr_num(parse, &arg1, &arg2, expr->op_type, result); } else /* eval as string */ { err = eval_expr_string(parse, &arg1, &arg2, expr->op_type, result); } } if (arg1.alloc) free(arg1.s); if (arg2.alloc) free(arg2.s); } #if DEBUG_EXPR_EVAL expand_arg(parse, _depth, "result", result); _depth--; #endif return STATUS_OK; } static NEOERR *var_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CSARG val; parse->escaping.current = NEOS_ESCAPE_NONE; err = eval_expr(parse, &(node->arg1), &val); if (err) return nerr_pass(err); if (val.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) { char buf[256]; long int n_val; n_val = arg_eval_num (parse, &val); snprintf (buf, sizeof(buf), "%ld", n_val); err = parse->output_cb (parse->output_ctx, buf); } else { char *s = arg_eval (parse, &val); /* Determine if the node has been escaped by an explicit function. If not * call to escape. node->escape should contain the default escaping from * Config.VarEscapeMode and parse->escaping.current will have a non-zero * value if an explicit escape call was made sooooo. */ if (s && parse->escaping.current == NEOS_ESCAPE_NONE) /* no explicit escape */ { char *escaped = NULL; /* Use default escape if escape is UNDEF */ if (node->escape == NEOS_ESCAPE_UNDEF) err = neos_var_escape(parse->escaping.when_undef, s, &escaped); else err = neos_var_escape(node->escape, s, &escaped); if (escaped) { err = parse->output_cb (parse->output_ctx, escaped); free(escaped); } } else if (s) { /* already explicitly escaped */ err = parse->output_cb (parse->output_ctx, s); } /* Do we set it to blank if s == NULL? */ } if (val.alloc) free(val.s); *next = node->next; return nerr_pass(err); } static NEOERR *lvar_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CSARG val; err = eval_expr(parse, &(node->arg1), &val); if (err) return nerr_pass(err); if (val.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) { char buf[256]; long int n_val; n_val = arg_eval_num (parse, &val); snprintf (buf, sizeof(buf), "%ld", n_val); err = parse->output_cb (parse->output_ctx, buf); } else { char *s = arg_eval (parse, &val); if (s) { CSPARSE *cs = NULL; /* Ok, we need our own copy of the string to pass to * cs_parse_string... */ if (val.alloc && (val.op_type & CS_TYPE_STRING)) { val.alloc = 0; } else { s = strdup(s); if (s == NULL) { return nerr_raise(NERR_NOMEM, "Unable to allocate memory for lvar_eval"); } } do { err = cs_init_internal(&cs, parse->hdf, parse); if (err) break; err = cs_parse_string(cs, s, strlen(s)); if (err) break; err = cs_render(cs, parse->output_ctx, parse->output_cb); if (err) break; } while (0); cs_destroy(&cs); } } if (val.alloc) free(val.s); *next = node->next; return nerr_pass(err); } static NEOERR *linclude_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CSARG val; err = eval_expr(parse, &(node->arg1), &val); if (err) return nerr_pass(err); if (val.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) { char buf[256]; long int n_val; n_val = arg_eval_num (parse, &val); snprintf (buf, sizeof(buf), "%ld", n_val); err = parse->output_cb (parse->output_ctx, buf); } else { char *s = arg_eval (parse, &val); if (s) { CSPARSE *cs = NULL; do { err = cs_init_internal(&cs, parse->hdf, parse); if (err) break; err = cs_parse_file(cs, s); if (!(node->flags & CSF_REQUIRED)) { nerr_handle(&err, NERR_NOT_FOUND); } if (err) break; err = cs_render(cs, parse->output_ctx, parse->output_cb); if (err) break; } while (0); cs_destroy(&cs); } } if (val.alloc) free(val.s); *next = node->next; return nerr_pass(err); } /* if the expr evaluates to true, display it, else render the alternate */ static NEOERR *alt_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CSARG val; int eval_true = 1; err = eval_expr(parse, &(node->arg1), &val); if (err) return nerr_pass(err); eval_true = arg_eval_bool(parse, &val); if (eval_true) { if (val.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) { char buf[256]; long int n_val; n_val = arg_eval_num (parse, &val); snprintf (buf, sizeof(buf), "%ld", n_val); err = parse->output_cb (parse->output_ctx, buf); } else { char *s = arg_eval (parse, &val); /* Do we set it to blank if s == NULL? */ if (s) { err = parse->output_cb (parse->output_ctx, s); } } } if (val.alloc) free(val.s); if (eval_true == 0) { err = render_node (parse, node->case_0); } *next = node->next; return nerr_pass(err); } /* just calls through to the child nodes */ static NEOERR *escape_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; /* TODO(wad): Should I set a eval-time value here? */ err = render_node (parse, node->case_0); *next = node->next; return nerr_pass(err); } static NEOERR *if_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; int eval_true = 0; CSARG val; err = eval_expr(parse, &(node->arg1), &val); if (err) return nerr_pass (err); eval_true = arg_eval_bool(parse, &val); if (val.alloc) free(val.s); if (eval_true) { err = render_node (parse, node->case_0); } else if (node->case_1 != NULL) { err = render_node (parse, node->case_1); } *next = node->next; return nerr_pass (err); } static NEOERR *else_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; STACK_ENTRY *entry; /* ne_warn ("else"); */ err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) return nerr_pass(err); parse->next = &(entry->tree->case_1); parse->current = entry->tree; return STATUS_OK; } static NEOERR *elif_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; STACK_ENTRY *entry; /* ne_warn ("elif: %s", arg); */ err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) return nerr_pass(err); if (entry->next_tree == NULL) entry->next_tree = entry->tree; parse->next = &(entry->tree->case_1); err = if_parse(parse, cmd, arg); entry->tree = parse->current; return nerr_pass(err); } static NEOERR *endif_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; STACK_ENTRY *entry; /* ne_warn ("endif"); */ err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) return nerr_pass(err); if (entry->next_tree) parse->next = &(entry->next_tree->next); else parse->next = &(entry->tree->next); parse->current = entry->tree; return STATUS_OK; } static NEOERR *each_with_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; char *lvar; char *p; char tmp[256]; err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; p = lvar = neos_strip(arg); while (*p && !isspace(*p) && *p != '=') p++; if (*p == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Improperly formatted %s directive: %s", find_context(parse, -1, tmp, sizeof(tmp)), Commands[cmd].cmd, arg); } if (*p != '=') { *p++ = '\0'; while (*p && *p != '=') p++; if (*p == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Improperly formatted %s directive: %s", find_context(parse, -1, tmp, sizeof(tmp)), Commands[cmd].cmd, arg); } p++; } else { *p++ = '\0'; } while (*p && isspace(*p)) p++; if (*p == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Improperly formatted %s directive: %s", find_context(parse, -1, tmp, sizeof(tmp)), Commands[cmd].cmd, arg); } node->arg1.op_type = CS_TYPE_VAR; node->arg1.s = lvar; err = parse_expr(parse, p, 0, &(node->arg2)); if (err) { dealloc_node(&node); return nerr_pass(err); } /* ne_warn ("each %s %s", lvar, p); */ *(parse->next) = node; parse->next = &(node->case_0); parse->current = node; return STATUS_OK; } static NEOERR *each_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CS_LOCAL_MAP each_map; CSARG val; HDF *var, *child; memset(&each_map, 0, sizeof(each_map)); err = eval_expr(parse, &(node->arg2), &val); if (err) return nerr_pass(err); if (val.op_type == CS_TYPE_VAR) { var = var_lookup_obj (parse, val.s); if (var != NULL) { /* Init and install local map */ each_map.type = CS_TYPE_VAR; each_map.name = node->arg1.s; each_map.next = parse->locals; each_map.first = 1; each_map.last = 0; parse->locals = &each_map; do { child = hdf_obj_child (var); while (child != NULL) { /* We don't explicitly set each_map.last here since checking * requires a function call, so we move the check to _builtin_last * so it only makes the call if last() is being used */ each_map.h = child; err = render_node (parse, node->case_0); if (each_map.map_alloc) { free(each_map.s); each_map.s = NULL; } if (each_map.first) each_map.first = 0; if (err != STATUS_OK) break; child = hdf_obj_next (child); } } while (0); /* Remove local map */ parse->locals = each_map.next; } } /* else WARNING */ if (val.alloc) free(val.s); *next = node->next; return nerr_pass (err); } static NEOERR *with_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CS_LOCAL_MAP with_map; CSARG val; HDF *var; memset(&with_map, 0, sizeof(with_map)); err = eval_expr(parse, &(node->arg2), &val); if (err) return nerr_pass(err); if (val.op_type == CS_TYPE_VAR) { var = var_lookup_obj (parse, val.s); if (var != NULL) { /* Init and install local map */ with_map.type = CS_TYPE_VAR; with_map.name = node->arg1.s; with_map.next = parse->locals; with_map.h = var; parse->locals = &with_map; err = render_node (parse, node->case_0); /* Remove local map */ if (with_map.map_alloc) free(with_map.s); parse->locals = with_map.next; } } else { /* else WARNING */ ne_warn("Invalid op_type for with: %s", expand_token_type(val.op_type, 1)); } if (val.alloc) free(val.s); *next = node->next; return nerr_pass (err); } static NEOERR *end_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; STACK_ENTRY *entry; err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) return nerr_pass(err); parse->next = &(entry->tree->next); parse->current = entry->tree; return STATUS_OK; } static NEOERR *include_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; char *s; int flags = 0; CSARG arg1, val; memset(&arg1, 0, sizeof(CSARG)); if (arg[0] == '!') flags |= CSF_REQUIRED; arg++; /* Validate arg is a var (regex /^[#" ]$/) */ err = parse_expr (parse, arg, 0, &arg1); if (err) return nerr_pass(err); /* ne_warn ("include: %s", a); */ err = eval_expr(parse, &arg1, &val); if (err) return nerr_pass(err); s = arg_eval (parse, &val); if (s == NULL && !(flags & CSF_REQUIRED)) return STATUS_OK; err = cs_parse_file(parse, s); if (!(flags & CSF_REQUIRED)) { nerr_handle(&err, NERR_NOT_FOUND); } if (val.alloc) free(val.s); return nerr_pass (err); } static NEOERR *def_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; CS_MACRO *macro; CSARG *carg, *larg = NULL; char *a = NULL, *p = NULL, *s; char tmp[256]; char name[256]; int x = 0; BOOL last = FALSE; /* Since def doesn't get a new stack entry until after this is run, * setup a dumb var on the parse object to hold the future setting. */ parse->escaping.next_stack = NEOS_ESCAPE_UNDEF; err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; arg++; s = arg; while (*s && *s != ' ' && *s != '#' && *s != '(') { name[x++] = *s; s++; } name[x] = '\0'; while (*s && isspace(*s)) s++; if (*s == '\0' || *s != '(') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Missing left paren in macro def %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } s++; /* Check to see if this is a redefinition */ macro = parse->macros; while (macro != NULL) { if (!strcmp(macro->name, name)) { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Duplicate macro def for %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } macro = macro->next; } macro = (CS_MACRO *) calloc (1, sizeof (CS_MACRO)); if (macro) macro->name = strdup(name); if (macro == NULL || macro->name == NULL) { dealloc_node(&node); dealloc_macro(¯o); return nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for CS_MACRO in def %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } while (*s) { while (*s && isspace(*s)) s++; a = strpbrk(s, ",)"); if (a == NULL) { err = nerr_raise (NERR_PARSE, "%s Missing right paren in def %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); break; } if (*a == ')') last = TRUE; *a = '\0'; /* cut out ending whitespace */ p = strpbrk(s, " \t\r\n"); if (p != NULL) *p = '\0'; p = strpbrk(s, "\"?<>=!#-+|&,)*/%[]( \t\r\n"); if (p != NULL) { err = nerr_raise (NERR_PARSE, "%s Invalid character in def %s argument: %c", find_context(parse, -1, tmp, sizeof(tmp)), arg, *p); break; } /* No argument case */ if (*s == '\0' && macro->n_args == 0) break; if (*s == '\0') { err = nerr_raise (NERR_PARSE, "%s Missing argument name or extra comma in def %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); break; } carg = (CSARG *) calloc (1, sizeof(CSARG)); if (carg == NULL) { err = nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for CSARG in def %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); break; } if (larg == NULL) { macro->args = carg; larg = carg; } else { larg->next = carg; larg = carg; } macro->n_args++; carg->s = s; if (last == TRUE) break; s = a+1; } if (err) { dealloc_node(&node); dealloc_macro(¯o); return nerr_pass(err); } macro->tree = node; if (parse->macros) { macro->next = parse->macros; } parse->macros = macro; *(parse->next) = node; parse->next = &(node->case_0); parse->current = node; return STATUS_OK; } static int rearrange_for_call(CSARG **args) { CSARG *larg = NULL; CSARG *carg = *args; CSARG *vargs = NULL; int nargs = 0; /* multiple argument case, we have to walk the args and reverse * them. Also handles single arg case since its the same as the * last arg */ while (carg) { nargs++; if (carg->op_type != CS_OP_COMMA) { /* last argument */ if (vargs) carg->next = vargs; vargs = carg; break; } if (vargs) carg->expr1->next = vargs; vargs = carg->expr1; larg = carg; carg = carg->next; /* dealloc comma, but not its descendents */ larg->next = NULL; larg->expr1 = NULL; dealloc_arg(&larg); } *args = vargs; return nargs; } static NEOERR *call_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; CS_MACRO *macro; CSARG *carg; char *s, *a = NULL; char tmp[256]; char name[256]; int x = 0; int nargs = 0; STACK_ENTRY *entry; err = uListGet (parse->stack, -1, (void *)&entry); if (err != STATUS_OK) return nerr_pass(err); err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; node->escape = entry->escape; arg++; s = arg; while (x < sizeof(name) && *s && *s != ' ' && *s != '#' && *s != '(') { name[x++] = *s; s++; } name[x] = '\0'; while (*s && isspace(*s)) s++; if (*s == '\0' || *s != '(') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Missing left paren in call %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } s++; /* Check to see if this macro exists */ macro = parse->macros; while (macro != NULL) { if (!strcmp(macro->name, name)) break; macro = macro->next; } if (macro == NULL) { dealloc_node(&node); err = nerr_raise (NERR_PARSE, "%s Undefined macro called: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); if (parse->audit_mode) { /* Ignore macros that cannot be found */ return _store_error(parse, err); } else { return err; } } node->arg1.op_type = CS_TYPE_MACRO; node->arg1.macro = macro; a = strrchr(s, ')'); if (a == NULL) { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Missing right paren in call %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } *a = '\0'; while (*s && isspace(*s)) s++; /* No arguments case */ if (*s == '\0') { nargs = 0; } else { /* Parse arguments case */ do { carg = (CSARG *) calloc (1, sizeof(CSARG)); if (carg == NULL) { err = nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for CSARG in call %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); break; } err = parse_expr (parse, s, 0, carg); if (err) break; nargs = rearrange_for_call(&carg); node->vargs = carg; } while (0); } if (!err && nargs != macro->n_args) { err = nerr_raise (NERR_PARSE, "%s Incorrect number of arguments, expected %d, got %d in call to macro %s: %s", find_context(parse, -1, tmp, sizeof(tmp)), macro->n_args, nargs, macro->name, arg); } if (err) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *call_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CS_LOCAL_MAP *call_map, *map; CS_MACRO *macro; CSARG *carg, *darg; HDF *var; int x; /* Reset the value of when_undef for the coming call evaluation. * This is only used here so it there's no need to reset its value after * the call. If this call is nested (escape == NEOS_ESCAPE_UNDEF), then * leave the when_undef variable alone. The parent call_eval should have * already defined it. */ if (node->escape != NEOS_ESCAPE_UNDEF) parse->escaping.when_undef = node->escape; macro = node->arg1.macro; if (macro->n_args) { call_map = (CS_LOCAL_MAP *) calloc (macro->n_args, sizeof(CS_LOCAL_MAP)); if (call_map == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for call_map in call_eval of %s", macro->name); } else { call_map = NULL; } darg = macro->args; carg = node->vargs; for (x = 0; x < macro->n_args; x++) { CSARG val; map = &call_map[x]; if (x) call_map[x-1].next = map; map->name = darg->s; err = eval_expr(parse, carg, &val); if (err) break; if (val.op_type & CS_TYPE_STRING) { map->s = val.s; map->type = val.op_type; map->map_alloc = val.alloc; val.alloc = 0; } else if (val.op_type & CS_TYPE_NUM) { map->n = val.n; map->type = CS_TYPE_NUM; } else if (val.op_type & (CS_TYPE_VAR | CS_TYPE_VAR_NUM)) { CS_LOCAL_MAP *lmap; char *c; lmap = lookup_map (parse, val.s, &c); if (lmap != NULL && (lmap->type != CS_TYPE_VAR && lmap->type != CS_TYPE_VAR_NUM)) { /* if we're referencing a local var which maps to a string or * number... then copy */ if (lmap->type == CS_TYPE_NUM) { map->n = lmap->n; map->type = lmap->type; } else { map->s = lmap->s; map->type = lmap->type; } } else { var = var_lookup_obj (parse, val.s); map->h = var; map->type = CS_TYPE_VAR; /* Bring across the name we're mapping to, in case h doesn't exist and * we need to set it. */ map->s = val.s; map->map_alloc = val.alloc; val.alloc = 0; } } else { ne_warn("Unsupported type %s in call_expr", expand_token_type(val.op_type, 1)); } if (val.alloc) free(val.s); map->next = parse->locals; darg = darg->next; carg = carg->next; } if (err == STATUS_OK) { map = parse->locals; if (macro->n_args) parse->locals = call_map; err = render_node (parse, macro->tree->case_0); parse->locals = map; } for (x = 0; x < macro->n_args; x++) { if (call_map[x].map_alloc) free(call_map[x].s); } if (call_map) free (call_map); *next = node->next; return nerr_pass(err); } static NEOERR *set_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; char *s; char tmp[256]; err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; arg++; s = arg; while (*s && *s != '=') s++; if (*s == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Missing equals in set %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } *s = '\0'; s++; err = parse_expr(parse, arg, 1, &(node->arg1)); if (err) { dealloc_node(&node); return nerr_pass(err); } err = parse_expr(parse, s, 0, &(node->arg2)); if (err) { dealloc_node(&node); return nerr_pass(err); } *(parse->next) = node; parse->next = &(node->next); parse->current = node; return STATUS_OK; } static NEOERR *set_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CSARG val; CSARG set; err = eval_expr(parse, &(node->arg1), &set); if (err) return nerr_pass (err); err = eval_expr(parse, &(node->arg2), &val); if (err) { if (set.alloc) free(set.s); return nerr_pass (err); } if (set.op_type != CS_TYPE_NUM) { /* this allow for a weirdness where set:"foo"="bar" * actually sets the hdf var foo... */ if (val.op_type & (CS_TYPE_NUM | CS_TYPE_VAR_NUM)) { char buf[256]; long int n_val; n_val = arg_eval_num (parse, &val); snprintf (buf, sizeof(buf), "%ld", n_val); if (set.s) { err = var_set_value (parse, set.s, buf); } else { err = nerr_raise(NERR_ASSERT, "lvalue is NULL/empty in attempt to evaluate set to '%s'", buf); } } else { char *s = arg_eval (parse, &val); /* Do we set it to blank if s == NULL? */ if (set.s) { err = var_set_value (parse, set.s, s); } else { err = nerr_raise(NERR_ASSERT, "lvalue is NULL/empty in attempt to evaluate set to '%s'", (s) ? s : ""); } } } /* else WARNING */ if (set.alloc) free(set.s); if (val.alloc) free(val.s); *next = node->next; return nerr_pass (err); } static NEOERR *loop_parse (CSPARSE *parse, int cmd, char *arg) { NEOERR *err; CSTREE *node; CSARG *carg, *larg = NULL; BOOL last = FALSE; char *lvar; char *p, *a; char tmp[256]; int x; err = alloc_node (&node, parse); if (err) return nerr_pass(err); node->cmd = cmd; if (arg[0] == '!') node->flags |= CSF_REQUIRED; arg++; p = lvar = neos_strip(arg); while (*p && !isspace(*p) && *p != '=') p++; if (*p == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Improperly formatted loop directive: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } if (*p != '=') { *p++ = '\0'; while (*p && *p != '=') p++; if (*p == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Improperly formatted loop directive: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } p++; } else { *p++ = '\0'; } while (*p && isspace(*p)) p++; if (*p == '\0') { dealloc_node(&node); return nerr_raise (NERR_PARSE, "%s Improperly formatted loop directive: %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); } node->arg1.op_type = CS_TYPE_VAR; node->arg1.s = lvar; x = 0; while (*p) { carg = (CSARG *) calloc (1, sizeof(CSARG)); if (carg == NULL) { err = nerr_raise (NERR_NOMEM, "%s Unable to allocate memory for CSARG in loop %s", find_context(parse, -1, tmp, sizeof(tmp)), arg); break; } if (larg == NULL) { node->vargs = carg; larg = carg; } else { larg->next = carg; larg = carg; } x++; a = strpbrk(p, ","); if (a == NULL) last = TRUE; else *a = '\0'; err = parse_expr (parse, p, 0, carg); if (err) break; if (last == TRUE) break; p = a+1; } if (!err && ((x < 1) || (x > 3))) { err = nerr_raise (NERR_PARSE, "%s Incorrect number of arguments, expected 1, 2, or 3 got %d in loop: %s", find_context(parse, -1, tmp, sizeof(tmp)), x, arg); } /* ne_warn ("loop %s %s", lvar, p); */ *(parse->next) = node; parse->next = &(node->case_0); parse->current = node; return STATUS_OK; } static NEOERR *loop_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { NEOERR *err = STATUS_OK; CS_LOCAL_MAP each_map; int var; int start = 0, end = 0, step = 1; int x, iter = 1; CSARG *carg; CSARG val; memset(&each_map, 0, sizeof(each_map)); carg = node->vargs; if (carg == NULL) return nerr_raise (NERR_ASSERT, "No arguments in loop eval?"); err = eval_expr(parse, carg, &val); if (err) return nerr_pass(err); end = arg_eval_num(parse, &val); if (val.alloc) free(val.s); if (carg->next) { start = end; carg = carg->next; err = eval_expr(parse, carg, &val); if (err) return nerr_pass(err); end = arg_eval_num(parse, &val); if (val.alloc) free(val.s); if (carg->next) { carg = carg->next; err = eval_expr(parse, carg, &val); if (err) return nerr_pass(err); step = arg_eval_num(parse, &val); if (val.alloc) free(val.s); } } if (((step < 0) && (start < end)) || ((step > 0) && (end < start))) { iter = 0; } else if (step == 0) { iter = 0; } else { iter = abs((end - start) / step + 1); } if (iter > 0) { /* Init and install local map */ each_map.type = CS_TYPE_NUM; each_map.name = node->arg1.s; each_map.next = parse->locals; each_map.first = 1; parse->locals = &each_map; var = start; for (x = 0, var = start; x < iter; x++, var += step) { if (x == iter - 1) each_map.last = 1; each_map.n = var; err = render_node (parse, node->case_0); if (each_map.map_alloc) { free(each_map.s); each_map.s = NULL; } if (each_map.first) each_map.first = 0; if (err != STATUS_OK) break; } /* Remove local map */ parse->locals = each_map.next; } *next = node->next; return nerr_pass (err); } static NEOERR *skip_eval (CSPARSE *parse, CSTREE *node, CSTREE **next) { *next = node->next; return STATUS_OK; } static NEOERR *render_node (CSPARSE *parse, CSTREE *node) { NEOERR *err = STATUS_OK; while (node != NULL) { /* ne_warn ("%s %08x", Commands[node->cmd].cmd, node); */ err = (*(Commands[node->cmd].eval_handler))(parse, node, &node); if (err) break; } return nerr_pass(err); } NEOERR *cs_render (CSPARSE *parse, void *ctx, CSOUTFUNC cb) { CSTREE *node; if (parse->tree == NULL) return nerr_raise (NERR_ASSERT, "No parse tree exists"); parse->output_ctx = ctx; parse->output_cb = cb; node = parse->tree; return nerr_pass (render_node(parse, node)); } /* **** Functions ******************************************** */ NEOERR *cs_register_function(CSPARSE *parse, const char *funcname, int n_args, CSFUNCTION function) { CS_FUNCTION *csf; /* Should we validate the parseability of the name? */ csf = parse->functions; while (csf != NULL) { if (!strcmp(csf->name, funcname) && csf->function != function) { return nerr_raise(NERR_DUPLICATE, "Attempt to register duplicate function %s", funcname); } csf = csf->next; } csf = (CS_FUNCTION *) calloc (1, sizeof(CS_FUNCTION)); if (csf == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory to register function %s", funcname); csf->name = strdup(funcname); if (csf->name == NULL) { free(csf); return nerr_raise(NERR_NOMEM, "Unable to allocate memory to register function %s", funcname); } csf->function = function; csf->n_args = n_args; csf->escape = NEOS_ESCAPE_NONE; csf->next = parse->functions; parse->functions = csf; return STATUS_OK; } /* This is similar to python's PyArg_ParseTuple, : * s - string (allocated) * i - int * A - arg ptr (maybe later) */ NEOERR * cs_arg_parsev(CSPARSE *parse, CSARG *args, const char *fmt, va_list ap) { NEOERR *err = STATUS_OK; char **s; long int *i; CSARG val; while (*fmt) { memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); switch (*fmt) { case 's': s = va_arg(ap, char **); if (s == NULL) { err = nerr_raise(NERR_ASSERT, "Invalid number of arguments in call to cs_arg_parse"); break; } *s = arg_eval_str_alloc(parse, &val); break; case 'i': i = va_arg(ap, long int *); if (i == NULL) { err = nerr_raise(NERR_ASSERT, "Invalid number of arguments in call to cs_arg_parse"); break; } *i = arg_eval_num(parse, &val); break; default: break; } if (err) return nerr_pass(err); fmt++; args = args->next; if (val.alloc) free(val.s); } if (err) return nerr_pass(err); return STATUS_OK; } NEOERR * cs_arg_parse(CSPARSE *parse, CSARG *args, const char *fmt, ...) { NEOERR *err; va_list ap; va_start(ap, fmt); err = cs_arg_parsev(parse, args, fmt, ap); va_end(ap); return nerr_pass(err); } static NEOERR * _builtin_subcount(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; HDF *obj; int count = 0; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); /* default for non-vars is 0 children */ result->op_type = CS_TYPE_NUM; result->n = 0; if (val.op_type & CS_TYPE_VAR) { obj = var_lookup_obj (parse, val.s); if (obj != NULL) { obj = hdf_obj_child(obj); while (obj != NULL) { count++; obj = hdf_obj_next(obj); } } result->n = count; } if (val.alloc) free(val.s); return STATUS_OK; } static NEOERR * _builtin_str_length(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); /* non var/string objects have 0 length */ result->op_type = CS_TYPE_NUM; result->n = 0; if (val.op_type & (CS_TYPE_VAR | CS_TYPE_STRING)) { char *s = arg_eval(parse, &val); if (s) result->n = strlen(s); } if (val.alloc) free(val.s); return STATUS_OK; } static NEOERR * _builtin_str_crc(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); /* non var/string objects have 0 length */ result->op_type = CS_TYPE_NUM; result->n = 0; if (val.op_type & (CS_TYPE_VAR | CS_TYPE_STRING)) { char *s = arg_eval(parse, &val); if (s) result->n = ne_crc((unsigned char *)s, strlen(s)); } if (val.alloc) free(val.s); return STATUS_OK; } static NEOERR * _builtin_str_find(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; char *s = NULL; char *substr = NULL; char *pstr = NULL; result->op_type = CS_TYPE_NUM; result->n = -1; err = cs_arg_parse(parse, args, "ss", &s, &substr); if (err) return nerr_pass(err); /* If null arguments, return -1 index */ if (s == NULL || substr == NULL) { if (s) free(s); if (substr) free(substr); return STATUS_OK; } pstr = strstr(s, substr); if (pstr != NULL) { result->n = (pstr - s) / sizeof(char); } free(s); free(substr); return STATUS_OK; } static NEOERR * _builtin_name(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; HDF *obj; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); result->op_type = CS_TYPE_STRING; result->s = ""; if (val.op_type & CS_TYPE_VAR) { obj = var_lookup_obj (parse, val.s); if (obj != NULL) result->s = hdf_obj_name(obj); } else if (val.op_type & CS_TYPE_STRING) { result->s = val.s; result->alloc = val.alloc; val.alloc = 0; } if (val.alloc) free(val.s); return STATUS_OK; } /* Check to see if a local variable is the first in an each/loop sequence */ static NEOERR * _builtin_first(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; CS_LOCAL_MAP *map; char *c; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); /* default is "not first" */ result->op_type = CS_TYPE_NUM; result->n = 0; /* Only applies to possible local vars */ if ((val.op_type & CS_TYPE_VAR) && !strchr(val.s, '.')) { map = lookup_map (parse, val.s, &c); if (map && map->first) result->n = 1; } if (val.alloc) free(val.s); return STATUS_OK; } /* Check to see if a local variable is the last in an each/loop sequence */ /* TODO: consider making this work on regular HDF vars */ static NEOERR * _builtin_last(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; CS_LOCAL_MAP *map; char *c; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); /* default is "not last" */ result->op_type = CS_TYPE_NUM; result->n = 0; /* Only applies to possible local vars */ if ((val.op_type & CS_TYPE_VAR) && !strchr(val.s, '.')) { map = lookup_map (parse, val.s, &c); if (map) { if (map->last) { result->n = 1; } else if (map->type == CS_TYPE_VAR) { if (hdf_obj_next(map->h) == NULL) { result->n = 1; } } } } if (val.alloc) free(val.s); return STATUS_OK; } /* returns the absolute value (ie, positive) of a number */ static NEOERR * _builtin_abs (CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; int n1 = 0; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); result->op_type = CS_TYPE_NUM; n1 = arg_eval_num(parse, &val); result->n = abs(n1); if (val.alloc) free(val.s); return STATUS_OK; } /* returns the larger or two integers */ static NEOERR * _builtin_max (CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; long int n1 = 0; long int n2 = 0; result->op_type = CS_TYPE_NUM; result->n = 0; err = cs_arg_parse(parse, args, "ii", &n1, &n2); if (err) return nerr_pass(err); result->n = (n1 > n2) ? n1 : n2; return STATUS_OK; } /* returns the smaller or two integers */ static NEOERR * _builtin_min (CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; long int n1 = 0; long int n2 = 0; result->op_type = CS_TYPE_NUM; result->n = 0; err = cs_arg_parse(parse, args, "ii", &n1, &n2); if (err) return nerr_pass(err); result->n = (n1 < n2) ? n1 : n2; return STATUS_OK; } static NEOERR * _builtin_str_slice (CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; char *s = NULL; char *slice; long int b = 0; long int e = 0; size_t len; result->op_type = CS_TYPE_STRING; result->s = ""; err = cs_arg_parse(parse, args, "sii", &s, &b, &e); if (err) return nerr_pass(err); /* If null, return empty string */ if (s == NULL) return STATUS_OK; len = strlen(s); if (b < 0 && e == 0) e = len; if (b < 0) b += len; if (e < 0) e += len; if (e > len) e = len; /* Its the whole string */ if (b == 0 && e == len) { result->s = s; result->alloc = 1; return STATUS_OK; } if (e < b) b = e; if (b == e) { /* If null, return empty string */ free(s); return STATUS_OK; } slice = (char *) malloc (sizeof(char) * (e-b+1)); if (slice == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory for string slice"); strncpy(slice, s + b, e-b); free(s); slice[e-b] = '\0'; result->s = slice; result->alloc = 1; return STATUS_OK; } #ifdef ENABLE_GETTEXT static NEOERR * _builtin_gettext(CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; char *s; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); result->op_type = CS_TYPE_STRING; result->s = ""; if (val.op_type & (CS_TYPE_VAR | CS_TYPE_STRING)) { s = arg_eval(parse, &val); if (s) { result->s = gettext(s); } } if (val.alloc) free(val.s); return STATUS_OK; } #endif static NEOERR * _str_func_wrapper (CSPARSE *parse, CS_FUNCTION *csf, CSARG *args, CSARG *result) { NEOERR *err; char *s; CSARG val; memset(&val, 0, sizeof(val)); err = eval_expr(parse, args, &val); if (err) return nerr_pass(err); if (val.op_type & (CS_TYPE_VAR | CS_TYPE_STRING)) { result->op_type = CS_TYPE_STRING; result->n = 0; s = arg_eval(parse, &val); if (s) { err = csf->str_func(s, &(result->s)); if (err) return nerr_pass(err); result->alloc = 1; } } else { result->op_type = val.op_type; result->n = val.n; result->s = val.s; result->alloc = val.alloc; val.alloc = 0; } if (val.alloc) free(val.s); return STATUS_OK; } NEOERR *cs_register_strfunc(CSPARSE *parse, char *funcname, CSSTRFUNC str_func) { NEOERR *err; err = cs_register_function(parse, funcname, 1, _str_func_wrapper); if (err) return nerr_pass(err); parse->functions->str_func = str_func; return STATUS_OK; } NEOERR *cs_register_esc_strfunc(CSPARSE *parse, char *funcname, CSSTRFUNC str_func) { NEOERR *err; err = cs_register_strfunc(parse, funcname, str_func); if (err) return nerr_pass(err); parse->functions->escape = NEOS_ESCAPE_FUNCTION; return STATUS_OK; } /* **** CS Initialize/Destroy ************************************ */ NEOERR *cs_init (CSPARSE **parse, HDF *hdf) { return nerr_pass(cs_init_internal(parse, hdf, NULL)); } static NEOERR *cs_init_internal (CSPARSE **parse, HDF *hdf, CSPARSE *parent) { NEOERR *err = STATUS_OK; CSPARSE *my_parse; STACK_ENTRY *entry; char *esc_value; CS_ESCAPE_MODES *esc_cursor; err = nerr_init(); if (err != STATUS_OK) return nerr_pass (err); my_parse = (CSPARSE *) calloc (1, sizeof (CSPARSE)); if (my_parse == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory for CSPARSE"); err = uListInit (&(my_parse->stack), 10, 0); if (err != STATUS_OK) { free(my_parse); return nerr_pass(err); } err = uListInit (&(my_parse->alloc), 10, 0); if (err != STATUS_OK) { free(my_parse); return nerr_pass(err); } err = alloc_node (&(my_parse->tree), my_parse); if (err != STATUS_OK) { cs_destroy (&my_parse); return nerr_pass(err); } my_parse->current = my_parse->tree; my_parse->next = &(my_parse->current->next); entry = (STACK_ENTRY *) calloc (1, sizeof (STACK_ENTRY)); if (entry == NULL) { cs_destroy (&my_parse); return nerr_raise (NERR_NOMEM, "Unable to allocate memory for stack entry"); } entry->state = ST_GLOBAL; entry->tree = my_parse->current; entry->location = 0; entry->escape = NEOS_ESCAPE_NONE; err = uListAppend(my_parse->stack, entry); if (err != STATUS_OK) { free (entry); cs_destroy(&my_parse); return nerr_pass(err); } my_parse->tag = hdf_get_value(hdf, "Config.TagStart", "cs"); my_parse->taglen = strlen(my_parse->tag); my_parse->hdf = hdf; /* Let's set the default escape data */ my_parse->escaping.global_ctx = NEOS_ESCAPE_NONE; my_parse->escaping.next_stack = NEOS_ESCAPE_NONE; my_parse->escaping.when_undef = NEOS_ESCAPE_NONE; /* See CS_ESCAPE_MODES. 0 is "none" */ esc_value = hdf_get_value(hdf, "Config.VarEscapeMode", EscapeModes[0].mode); /* Let's ensure the specified escape mode is valid and proceed */ for (esc_cursor = &EscapeModes[0]; esc_cursor->mode != NULL; esc_cursor++) if (!strcmp(esc_value, esc_cursor->mode)) { my_parse->escaping.global_ctx = esc_cursor->context; my_parse->escaping.next_stack = esc_cursor->context; entry->escape = esc_cursor->context; break; } /* Didn't find an acceptable value we were looking for */ if (esc_cursor->mode == NULL) { cs_destroy (&my_parse); return nerr_raise (NERR_OUTOFRANGE, "Invalid HDF value for Config.VarEscapeMode (none,html,js,url): %s", esc_value); } /* Read configuration value to determine whether to enable audit mode */ my_parse->audit_mode = hdf_get_int_value(hdf, "Config.EnableAuditMode", 0); my_parse->err_list = NULL; if (parent == NULL) { static struct _builtin_functions { const char *name; int nargs; CSFUNCTION function; } Builtins[] = { { "len", 1, _builtin_subcount }, { "subcount", 1, _builtin_subcount }, { "name", 1, _builtin_name }, { "first", 1, _builtin_first }, { "last", 1, _builtin_last }, { "abs", 1, _builtin_abs }, { "max", 2, _builtin_max }, { "min", 2, _builtin_min }, { "string.find", 2, _builtin_str_find }, { "string.slice", 3, _builtin_str_slice }, { "string.length", 1, _builtin_str_length }, { "string.crc", 1, _builtin_str_crc}, #ifdef ENABLE_GETTEXT { "_", 1, _builtin_gettext }, #endif { NULL, 0, NULL }, }; int x = 0; while (Builtins[x].name != NULL) { err = cs_register_function(my_parse, Builtins[x].name, Builtins[x].nargs, Builtins[x].function); if (err) { cs_destroy(&my_parse); return nerr_pass(err); } x++; } /* Set global_hdf to be null */ my_parse->global_hdf = NULL; my_parse->parent = NULL; } else { /* TODO: macros and functions should actually not be duplicated, they * should just be modified in lookup to walk the CS struct hierarchy we're * creating here */ /* BUG: We currently can't copy the macros because they reference the parse * tree, so if this sub-parse tree adds a macro, the macro reference will * persist, but the parse tree it points to will be gone when the sub-parse * is gone. */ my_parse->functions = parent->functions; my_parse->global_hdf = parent->global_hdf; my_parse->fileload = parent->fileload; my_parse->fileload_ctx = parent->fileload_ctx; // This should be safe since locals handling is done entirely local to the // eval functions, not globally by the parse handling. This should // pass the locals down to the new parse context to make locals work with // lvar my_parse->locals = parent->locals; my_parse->parent = parent; /* Copy the audit flag from parent */ my_parse->audit_mode = parent->audit_mode; } *parse = my_parse; return STATUS_OK; } void cs_register_fileload(CSPARSE *parse, void *ctx, CSFILELOAD fileload) { if (parse != NULL) { parse->fileload_ctx = ctx; parse->fileload = fileload; } } void cs_destroy (CSPARSE **parse) { CSPARSE *my_parse = *parse; if (my_parse == NULL) return; uListDestroy (&(my_parse->stack), ULIST_FREE); uListDestroy (&(my_parse->alloc), ULIST_FREE); dealloc_macro(&my_parse->macros); dealloc_node(&(my_parse->tree)); if (my_parse->parent == NULL) { dealloc_function(&(my_parse->functions)); } /* Free list of errors */ if (my_parse->err_list != NULL) { CS_ERROR *ptr; while (my_parse->err_list) { ptr = my_parse->err_list->next; free(my_parse->err_list->err); free(my_parse->err_list); my_parse->err_list = ptr; } } free(my_parse); *parse = NULL; } /* **** CS Debug Dumps ******************************************** */ static NEOERR *dump_node (CSPARSE *parse, CSTREE *node, int depth, void *ctx, CSOUTFUNC cb, char *buf, int blen) { NEOERR *err; while (node != NULL) { snprintf (buf, blen, "%*s %s ", depth, "", Commands[node->cmd].cmd); err = cb (ctx, buf); if (err) return nerr_pass (err); if (node->cmd) { if (node->arg1.op_type) { if (node->arg1.op_type == CS_TYPE_NUM) { snprintf (buf, blen, "%ld ", node->arg1.n); } else if (node->arg1.op_type == CS_TYPE_MACRO) { snprintf (buf, blen, "%s ", node->arg1.macro->name); } else { snprintf (buf, blen, "%s ", node->arg1.s); } err = cb (ctx, buf); if (err) return nerr_pass (err); } if (node->arg2.op_type) { if (node->arg2.op_type == CS_TYPE_NUM) { snprintf (buf, blen, "%ld", node->arg2.n); } else { snprintf (buf, blen, "%s", node->arg2.s); } err = cb (ctx, buf); if (err) return nerr_pass (err); } if (node->vargs) { CSARG *arg; arg = node->vargs; while (arg) { if (arg->op_type == CS_TYPE_NUM) { snprintf (buf, blen, "%ld ", arg->n); } else { snprintf (buf, blen, "%s ", arg->s); } err = cb (ctx, buf); if (err) return nerr_pass (err); arg = arg->next; } } } err = cb (ctx, "\n"); if (err) return nerr_pass (err); if (node->case_0) { snprintf (buf, blen, "%*s %s\n", depth, "", "Case 0"); err = cb (ctx, buf); if (err) return nerr_pass (err); err = dump_node (parse, node->case_0, depth+1, ctx, cb, buf, blen); if (err) return nerr_pass (err); } if (node->case_1) { snprintf (buf, blen, "%*s %s\n", depth, "", "Case 1"); err = cb (ctx, buf); if (err) return nerr_pass (err); err = dump_node (parse, node->case_1, depth+1, ctx, cb, buf, blen); if (err) return nerr_pass (err); } node = node->next; } return STATUS_OK; } NEOERR *cs_dump (CSPARSE *parse, void *ctx, CSOUTFUNC cb) { CSTREE *node; char buf[4096]; if (parse->tree == NULL) return nerr_raise (NERR_ASSERT, "No parse tree exists"); node = parse->tree; return nerr_pass (dump_node (parse, node, 0, ctx, cb, buf, sizeof(buf))); } #if 0 static char *node_name (CSTREE *node) { static char buf[256]; if (node == NULL) snprintf (buf, sizeof(buf), "NULL"); else snprintf (buf, sizeof(buf), "%s_%08x", Commands[node->cmd].cmd, node->node_num); return buf; } static NEOERR *dump_node_pre_c (CSPARSE *parse, CSTREE *node, FILE *fp) { NEOERR *err; while (node != NULL) { fprintf (fp, "CSTREE %s;\n", node_name(node)); if (node->case_0) { err = dump_node_pre_c (parse, node->case_0, fp); if (err != STATUS_OK) nerr_pass (err); } if (node->case_1) { err = dump_node_pre_c (parse, node->case_1, fp); if (err != STATUS_OK) nerr_pass (err); } node = node->next; } return STATUS_OK; } static NEOERR *dump_node_c (CSPARSE *parse, CSTREE *node, FILE *fp) { NEOERR *err; char *s; while (node != NULL) { fprintf (fp, "CSTREE %s =\n\t{%d, %d, %d, ", node_name(node), node->node_num, node->cmd, node->flags); s = repr_string_alloc (node->arg1.s); if (s == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate space for repr"); fprintf (fp, "\n\t { %d, %s, %ld }, ", node->arg1.op_type, s, node->arg1.n); free(s); s = repr_string_alloc (node->arg2.s); if (s == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate space for repr"); fprintf (fp, "\n\t { %d, %s, %ld }, ", node->arg2.op_type, s, node->arg2.n); free(s); if (node->case_0) fprintf (fp, "\n\t%d, &%s, ", node->op, node_name(node->case_0)); else fprintf (fp, "\n\t%d, NULL, ", node->op); if (node->case_1) fprintf (fp, "&%s, ", node_name(node->case_1)); else fprintf (fp, "NULL, "); if (node->next) fprintf (fp, "&%s};\n\n", node_name(node->next)); else fprintf (fp, "NULL};\n\n"); if (node->case_0) { err = dump_node_c (parse, node->case_0, fp); if (err != STATUS_OK) nerr_pass (err); } if (node->case_1) { err = dump_node_c (parse, node->case_1, fp); if (err != STATUS_OK) nerr_pass (err); } node = node->next; } return STATUS_OK; } NEOERR *cs_dump_c (CSPARSE *parse, char *path) { CSTREE *node; FILE *fp; NEOERR *err; if (parse->tree == NULL) return nerr_raise (NERR_ASSERT, "No parse tree exists"); fp = fopen(path, "w"); if (fp == NULL) { return nerr_raise (NERR_SYSTEM, "Unable to open file %s for writing: [%d] %s", path, errno, strerror(errno)); } fprintf(fp, "/* Auto-generated file: DO NOT EDIT */\n"); fprintf(fp, "#include \n\n"); fprintf(fp, "#include \"cs.h\"\n"); node = parse->tree; err = dump_node_pre_c (parse, node, fp); fprintf(fp, "\n"); err = dump_node_c (parse, node, fp); fclose(fp); return nerr_pass (err); } #endif clearsilver-0.10.5/cs/cstest.c0000644001211700116100000000442410405132247013104 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include "util/neo_misc.h" #include "util/neo_hdf.h" #include "cs.h" static NEOERR *output (void *ctx, char *s) { printf ("%s", s); return STATUS_OK; } NEOERR *test_strfunc(const char *str, char **ret) { char *s = strdup(str); int x = 0; if (s == NULL) return nerr_raise(NERR_NOMEM, "Unable to duplicate string in test_strfunc"); while (s[x]) { s[x] = tolower(s[x]); x++; } *ret = s; return STATUS_OK; } int main (int argc, char *argv[]) { NEOERR *err; CSPARSE *parse; HDF *hdf; int verbose = 0; char *hdf_file, *cs_file; if (argc < 3) { ne_warn ("Usage: cstest [-v] "); return -1; } if (!strcmp(argv[1], "-v")) { verbose = 1; if (argc < 4) { ne_warn ("Usage: cstest [-v] "); return -1; } hdf_file = argv[2]; cs_file = argv[3]; } else { hdf_file = argv[1]; cs_file = argv[2]; } err = hdf_init(&hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = hdf_read_file(hdf, hdf_file); if (err != STATUS_OK) { nerr_log_error(err); return -1; } printf ("Parsing %s\n", cs_file); err = cs_init (&parse, hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } /* register a test strfunc */ err = cs_register_strfunc(parse, "test_strfunc", test_strfunc); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = cs_parse_file (parse, cs_file); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } err = cs_render(parse, NULL, output); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } if (verbose) { printf ("\n-----------------------\nCS DUMP\n"); err = cs_dump(parse, NULL, output); } cs_destroy (&parse); if (verbose) { printf ("\n-----------------------\nHDF DUMP\n"); hdf_dump (hdf, NULL); } hdf_destroy(&hdf); return 0; } clearsilver-0.10.5/cs/test.cs0000644001211700116100000000227410465716057012757 00000000000000 Start of File Blah == wow Blah != wow wow (true) other (false) This is True x = x.num = This is True. wow This is False. Outside Inside = TestIf == 0 TestIf == 1 TestIf == else Correct, "1" == "1" WRONG, "1" != "1" between comments More? clearsilver-0.10.5/cs/test.cs.gold0000644001211700116100000001135010616225374013671 00000000000000Parsing test.cs Start of File Blah == wow wow (true) This is True wow I'm in test2.cs wow2 I'm in test2.cs wow2 escape: not used UrlArg: Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? BlahJs: quote ' backslash \ semicolon ; end tag Title: escape: none UrlArg: Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? BlahJs: quote ' backslash \ semicolon ; end tag Title: escape: html UrlArg: Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? BlahJs: quote ' backslash \ semicolon ; end tag </script> Title: </title><script>alert(1)</script> escape: js UrlArg: Secret Password~!@#$%^\x26*()+=-_|\x5C[]{}:\x22\x3B\x27\x3C\x3E,.? BlahJs: quote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E Title: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3E escape: url UrlArg: Secret+Password%7E!%40%23%24%25%5E%26*()%2B%3D-_%7C%5C%5B%5D%7B%7D%3A%22%3B%27%3C%3E%2C.%3F BlahJs: quote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E Title: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3E Nested escaping: html The internal calls should take precedence url -> UrlArg: Secret+Password%7E!%40%23%24%25%5E%26*()%2B%3D-_%7C%5C%5B%5D%7B%7D%3A%22%3B%27%3C%3E%2C.%3F js -> BlahJs: quote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html -> Title: </title><script>alert(1)</script> Defining the macro echo_all inside of a "html" escape. Calling echo_all() macro: not used: quote ' backslash \ semicolon ; end tag none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> Calling echo_all() macro from within "html": not used: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> Calling echo_all() macro from within "js": not used: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> Calling echo_all() macro from within "url": not used: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> not used: </title><script>alert(1)</script> none: url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3E html: </title><script>alert(1)</script> x = zero x.num = #0 This is True. wow x = one x.num = This is True. wow x = two x.num = #2 This is True. wow x = three x.num = This is True. wow This is False. Outside 0 Inside = 0 Inside = 1 Outside 1 Inside = 2 Inside = 3 Outside 2 Inside = 2 Inside = 3 Outside 3 TestIf == 0 Correct, "1" == "1" between comments More? clearsilver-0.10.5/cs/test.hdf0000644001211700116100000000431710465716057013113 00000000000000 Config.VarEscapeMode = none arg1 = 1 var = Empty = Numbers { hdf9 = 9 hdf14 = 14 } Blah = wow BlahJs = quote ' backslash \ semicolon ; end tag Title = UrlArg = Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? Foo = Worn Out Foo.Bar.Baz { 0 = zero 0.num = #0 1 = one 2 = two 2.num = #2 3 = three } Wow.Foo = 3 Outside { 0 { Inside { 0 = 0 1 = 1 } } 1 { Inside { 2 = 2 3 = 3 } } 2 : Outside.1 3 { } } TestIf = 0 Days { 0 = 0 0.Abbr = Mon 1 = 1 1.Abbr = Tues 2 = 2 2.Abbr = Wed 3 = 3 3.Abbr = Thur 4 = 4 4.Abbr = Fri 5 = 5 5.Abbr = Sat 6 = 6 6.Abbr = Sun } Neg = -1 My.Test : Days.0.Abbr My.Test2 : Days.0 Color = #fffff CGI.box.msgs { 0 { ticket_id = 1 } 1 { ticket_id = 2 } 2 { ticket_id = 3 } } Query.boxid = 2 Query.split = 1 Query.filter = 0 Query.sort = t Query.sort_dir = u CGI.box.cur.min_box_idx = 1 Files.0.Name = Desktop Files.0.Type = dir Files.0.Sub.0.Name = Bookmarks.html Files.0.Sub.0.Type = file Files.0.Sub.1.Name = History.txt Files.0.Sub.1.Type = file Files.0.Sub.2.Name = Resume.doc Files.0.Sub.2.Type = file Files.0.Sub.3.Name = Favorites Files.0.Sub.3.Type = dir Files.0.Sub.3.Sub.0.Name = foo Files.0.Sub.3.Sub.0.Type = file Files.0.Sub.3.Sub.1.Name = bar Files.0.Sub.3.Sub.1.Type = file Files.0.Sub.3.Sub.2.Name = boo Files.0.Sub.3.Sub.2.Type = file Files.0.Sub.3.Sub.3.Name = baz Files.0.Sub.3.Sub.3.Type = file Files.0.Sub.3.Sub.4.Name = faq Files.0.Sub.3.Sub.4.Type = file Files.0.Sub.3.Sub.5.Name = far Files.0.Sub.3.Sub.5.Type = file Files.1.Name = .cshrc Files.1.Type = file Files.2.Name = .login Files.2.Type = file Files.2.Name = Mail Files.2.Type = dir Files.2.Sub.0.Name = inbox Files.2.Sub.0.Type = file Files.2.Sub.1.Name = received Files.2.Sub.1.Type = file Files.2.Sub.2.Name = sent Files.2.Sub.2.Type = file Files.2.Sub.2.Name = postponed Files.2.Sub.2.Type = file EvarTests { 0 = ERROR 1 = test1 2 = test 2 } CS_START = A = HELLO B = WORLD C = / Biz.Address2 = addr parent_id = -1 faq.topic_id = 1 Query.topic = -1 faq.sub_topic_id = -1 clearsilver-0.10.5/cs/test10.cs0000644001211700116100000000064710261037506013107 00000000000000test new alt tag this should always display [1] ERROR: this shouldn't display (static string) ERROR: this should never display (#1) ERROR: this should never display (Foo.Bar.Baz.0 exists) This should display [3] clearsilver-0.10.5/cs/test10.cs.gold0000644001211700116100000000020710616225375014032 00000000000000Parsing test10.cs test new alt tag this should always display [1] this should display [2] 1 zero zero This should display [3] clearsilver-0.10.5/cs/test11.cs0000644001211700116100000000164010261037507013103 00000000000000 testing parenthesis for order of operations == 40 == 7 == 19 == 35 == 40 == 40 == 81 == 46 == 49 testing brackets for hdf var arrays == 0 == 1 == 2 == Mon == Tues == Wed == 2 3 == clearsilver-0.10.5/cs/test11.cs.gold0000644001211700116100000000073110616225375014035 00000000000000Parsing test11.cs testing parenthesis for order of operations 40 == 40 7 == 7 19 == 19 35 == 35 40 == 40 40 == 40 81 == 81 46 == 46 49 == 49 testing brackets for hdf var arrays 9 0 == 0 1 == 1 2 == 2 Mon == Mon Tues == Tues Wed == Wed 2 3 == 2 3 1 == 1 2 == 2 3 == 3 4 == 4 5 == 5 6 == 6 7 == 7 8 == 8 9 == 9 10 == 10 11 == 11 12 == 12 13 == 13 14 == 14 15 == 15 16 == 16 17 == 17 18 == 18 19 == 19 20 == 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 clearsilver-0.10.5/cs/test12.cs0000644001211700116100000000134310261037507013104 00000000000000

clearsilver-0.10.5/cs/test12.cs.gold0000644001211700116100000000243110616225375014035 00000000000000Parsing test12.cs
  • Desktop
    • Bookmarks.html
    • History.txt
    • Resume.doc
    • Favorites
      • foo
      • bar
      • boo
      • baz
      • faq
      • far
  • .cshrc
  • Mail
    • inbox
    • received
    • postponed
Desktop
 Bookmarks.html
 History.txt
 Resume.doc
 Favorites
  foo
  bar
  boo
  baz
  faq
  far
.cshrc
Mail
 inbox
 received
 postponed
clearsilver-0.10.5/cs/test13.cs0000644001211700116100000000022710512567365013116 00000000000000 clearsilver-0.10.5/cs/test13.cs.gold0000644001211700116100000000010110616225375014026 00000000000000Parsing test13.cs Worn Out test1 test 2 wow Worn Out clearsilver-0.10.5/cs/test14.cs0000644001211700116100000000342210261037507013106 00000000000000 Existence Tests All numbers exist ERROR All strings exist ERROR All expressions exist ERROR Exists ERROR Exists ERROR ERROR Blooey doesn't exist Blooey doesn't exist ERROR ERROR Blooey doesn't exist (implied) Blooey doesn't exist (implied negative) ERROR ERROR CORRECT boolean test, blooey doesn't exist, testif == 0 so its false explicit existence test ERROR testing not op Testing not zero ERROR ERROR Testing not one Testing not exist var one ERROR ERROR not expression existence test not expression test ERROR ERROR not expression test array exists test PASS ERROR array element exists test PASS ERROR array element exists test false ERROR PASS clearsilver-0.10.5/cs/test14.cs.gold0000644001211700116100000000123010616225375014033 00000000000000Parsing test14.cs Existence Tests All numbers exist All strings exist All expressions exist Blah Exists Foo Exists Blooey doesn't exist Blooey doesn't exist Blooey doesn't exist (implied) Blooey doesn't exist (implied negative) CORRECT boolean test, blooey doesn't exist, testif == 0 so its false explicit existence test testing not op Testing not zero Testing not one Testing not exist var one not expression existence test not expression test not expression test array exists test 0 PASS array element exists test Mon PASS array element exists test false PASS clearsilver-0.10.5/cs/test15.cs0000644001211700116100000000031210261037507013102 00000000000000 test functions string.length == 31 subcount == 4 len (depreciated) == 4 clearsilver-0.10.5/cs/test15.cs.gold0000644001211700116100000000014710616225375014042 00000000000000Parsing test15.cs test functions string.length 31 == 31 subcount 4 == 4 len (depreciated) 4 == 4 clearsilver-0.10.5/cs/test16.cs0000644001211700116100000000014310542107010013072 00000000000000 clearsilver-0.10.5/cs/test16.cs.gold0000644001211700116100000000020510616225375014036 00000000000000Parsing test16.cs HELLO/WORLD HELLO/WORLD HELLO/WORLD 0/WORLD 1/WORLD 2/WORLD 3/WORLD 4/WORLD 5/WORLD 6/WORLD clearsilver-0.10.5/cs/test17.cs0000644001211700116100000000114110261037507013105 00000000000000 Test from Chuck Simmons for setting of null value " + val + "" ?> Biz.Address2 = Biz.Address3 = clearsilver-0.10.5/cs/test17.cs.gold0000644001211700116100000000024510616225375014043 00000000000000Parsing test17.cs Test from Chuck Simmons for setting of null value Biz.Address2 = addr Biz.Address3 = clearsilver-0.10.5/cs/test18.cs0000644001211700116100000000136610261037507013117 00000000000000 .... with whitespace with extra variable With whitespace in def... .... clearsilver-0.10.5/cs/test18.cs.gold0000644001211700116100000000032410616225375014042 00000000000000Parsing test18.cs .... with whitespace .... with extra variable With whitespace in def... .... clearsilver-0.10.5/cs/test19.cs0000644001211700116100000000056310357065027013122 00000000000000 a: b: !a || b: !(a || b): Wow.Foo exists Wow.Bar exists 3: 2: clearsilver-0.10.5/cs/test19.cs.gold0000644001211700116100000000032210616225375014041 00000000000000Parsing test19.cs a: 0 b: 0 !a || b: 1 !(a || b): 1 a: 0 b: 1 !a || b: 1 !(a || b): 0 a: 1 b: 0 !a || b: 0 !(a || b): 0 a: 1 b: 1 !a || b: 1 !(a || b): 0 Wow.Foo exists 3 3: 3 2: 2 clearsilver-0.10.5/cs/test2.cs0000644001211700116100000000010110261037507013012 00000000000000 I'm in test2.cs I'm in an if wow2 clearsilver-0.10.5/cs/test2.cs.gold0000644001211700116100000000005110616225374013747 00000000000000Parsing test2.cs I'm in test2.cs wow2 clearsilver-0.10.5/cs/test3.cs0000644001211700116100000000313210261037507013022 00000000000000 before weekday before echo echo a variable: 3 echo a string: hellow world echo a number: 5 echo a variable: 3 echo a string: hellow world echo a number: 5 these tests show that local variables are live in sub calls echo a variable: 3 echo a string: hellow world echo a number: 5 after echo == testing macro calls in local vars in an each clearsilver-0.10.5/cs/test3.cs.gold0000644001211700116100000000131010616225374013747 00000000000000Parsing test3.cs before weekday Thur Fri before echo echo a variable: 3 3 echo a string: hellow world hello world echo a number: 5 5 echo a variable: 3 3 echo a string: hellow world hello world echo a number: 5 5 these tests show that local variables are live in sub calls echo a variable: 3 3 echo a string: hellow world hello world echo a number: 5 5 after echo testing macro calls in local vars in an each 0 == Mon Mon 1 == Tues Tues 2 == Wed Wed 3 == Thur Thur 4 == Fri Fri 5 == Sat Sat 6 == Sun Sun clearsilver-0.10.5/cs/test4.cs0000644001211700116100000000443310261037507013030 00000000000000 Testing cs set 5 % 2 == true ERROR! um, wrong? 5 % 2 == false? um, wrong? ERROR! 4 % 2 == true? 4 % 2 == false #0 ?> Yes, 4 > 0 ERROR! Wrong, 4 is not < 0 ERROR! 4 > 0 right, 4 > 0 right, 0 <= 5 ERROR! 0 <= 5 = #5 ?> ERROR! 0 >= 5 right, 0 >= 5 right "0" <= #5 ERROR! "0" <= #5 #14 ?> ERROR! "9" > #14 right "9" < #14 "14" ?> ERROR "9" > "14" (strings) right "9" < "14" (strings) Numbers.hdf14 ?> ERROR! hdf 9 > hdf 14 right hdf "9" < hdf "14" clearsilver-0.10.5/cs/test4.cs.gold0000644001211700116100000000156110616225374013760 00000000000000Parsing test4.cs Testing cs set 30 Worn Out wow 6 The end of the world. 5 % 2 == true 4 % 2 == false Yes, 4 > 0 right, 4 > 0 right, 0 <= 5 right, 0 >= 5 right "0" <= #5 right "9" < #14 right "9" < "14" (strings) right hdf "9" < hdf "14" /box_bm_body_frm.cs?boxid=2&cur=1&idx_cur=1&split=1&filter=0&sort=t&sort_dir=u&from_search= /box_bm_body_frm.cs?boxid=2&cur=2&idx_cur=1&split=1&filter=0&sort=t&sort_dir=u&from_search= /box_bm_body_frm.cs?boxid=2&cur=3&idx_cur=1&split=1&filter=0&sort=t&sort_dir=u&from_search= /box_bm_body_frm.cs?boxid=&cur=1&idx_cur=1&split=&filter=&sort=&sort_dir=&from_search= /box_bm_body_frm.cs?boxid=&cur=2&idx_cur=1&split=&filter=&sort=&sort_dir=&from_search= /box_bm_body_frm.cs?boxid=&cur=3&idx_cur=1&split=&filter=&sort=&sort_dir=&from_search= clearsilver-0.10.5/cs/test5.cs0000644001211700116100000000040710261037507013026 00000000000000 Correct, Neg is -1 ERROR! blah2 = clearsilver-0.10.5/cs/test5.cs.gold0000644001211700116100000000010510616225374013752 00000000000000Parsing test5.cs Correct, Neg is -1 blah2 = 20 Mon Mon clearsilver-0.10.5/cs/test6.cs0000644001211700116100000000045210261037507013027 00000000000000 Testing existence Color=Color (CORRECT) ERROR Testing not existence Correct, doesn't exist ERROR, doesn't exist ERROR, doesn't exist Correct, doesn't exist clearsilver-0.10.5/cs/test6.cs.gold0000644001211700116100000000021410616225374013754 00000000000000Parsing test6.cs Testing existence Color=Color (CORRECT) Testing not existence Correct, doesn't exist Correct, doesn't exist clearsilver-0.10.5/cs/test7.cs0000644001211700116100000000066710261037510013032 00000000000000 LOOP Test 1, 3, 5 , 1, 3, 5... 205 , backwards , broken , , clearsilver-0.10.5/cs/test7.cs.gold0000644001211700116100000000203010616225375013754 00000000000000Parsing test7.cs LOOP Test 1, 3, 5 1, 3, 5, 1, 3, 5... 205 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199, 201, 203, 205, backwards 205, 203, 201, 199, 197, 195, 193, 191, 189, 187, 185, 183, 181, 179, 177, 175, 173, 171, 169, 167, 165, 163, 161, 159, 157, 155, 153, 151, 149, 147, 145, 143, 141, 139, 137, 135, 133, 131, 129, 127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1, broken 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, clearsilver-0.10.5/cs/test8.cs0000644001211700116100000000024110261037510013017 00000000000000 some tests for new var is an expression clearsilver-0.10.5/cs/test8.cs.gold0000644001211700116100000000014010616225375013755 00000000000000Parsing test8.cs some tests for new var is an expression 5 6 big is better wow potato zero clearsilver-0.10.5/cs/test9.cs0000644001211700116100000000021310261037510013017 00000000000000Test for bug where in certain cases we didn't find the ending cs tag if there was a newline clearsilver-0.10.5/cs/test9.cs.gold0000644001211700116100000000015710616225375013766 00000000000000Parsing test9.cs Test for bug where in certain cases we didn't find the ending cs tag if there was a newline clearsilver-0.10.5/cs/test_abs_max_min.cs0000644001211700116100000000152110305650774015302 00000000000000 abs(-10) = abs("-10") = abs("10") = abs("0") = abs() = min(5,10) = min(-5,10) = min(-5,-10) = min(5,-10) = max(5,10) = max(-5,10) = max(-5,-10) = max(5,-10) = max(, ) = max(, ) = min(, ) = min(, ) = clearsilver-0.10.5/cs/test_abs_max_min.cs.gold0000644001211700116100000004600710616225375016236 00000000000000Parsing test_abs_max_min.cs abs(-10) = 10 abs("-10") = 10 abs("10") = 10 abs("0") = 0 abs(-5) = 5 abs(-4) = 4 abs(-3) = 3 abs(-2) = 2 abs(-1) = 1 abs(0) = 0 abs(1) = 1 abs(2) = 2 abs(3) = 3 abs(4) = 4 abs(5) = 5 min(5,10) = 5 min(-5,10) = -5 min(-5,-10) = -10 min(5,-10) = -10 max(5,10) = 10 max(-5,10) = 10 max(-5,-10) = -5 max(5,-10) = 5 max(-10, -10) = -10 max(-10, -10) = -10 min(-10, -10) = -10 min(-10, -10) = -10 max(-10, -8) = -8 max(-8, -10) = -8 min(-10, -8) = -10 min(-8, -10) = -10 max(-10, -6) = -6 max(-6, -10) = -6 min(-10, -6) = -10 min(-6, -10) = -10 max(-10, -4) = -4 max(-4, -10) = -4 min(-10, -4) = -10 min(-4, -10) = -10 max(-10, -2) = -2 max(-2, -10) = -2 min(-10, -2) = -10 min(-2, -10) = -10 max(-10, 0) = 0 max(0, -10) = 0 min(-10, 0) = -10 min(0, -10) = -10 max(-10, 2) = 2 max(2, -10) = 2 min(-10, 2) = -10 min(2, -10) = -10 max(-10, 4) = 4 max(4, -10) = 4 min(-10, 4) = -10 min(4, -10) = -10 max(-10, 6) = 6 max(6, -10) = 6 min(-10, 6) = -10 min(6, -10) = -10 max(-10, 8) = 8 max(8, -10) = 8 min(-10, 8) = -10 min(8, -10) = -10 max(-10, 10) = 10 max(10, -10) = 10 min(-10, 10) = -10 min(10, -10) = -10 max(-9, -10) = -9 max(-10, -9) = -9 min(-9, -10) = -10 min(-10, -9) = -10 max(-9, -8) = -8 max(-8, -9) = -8 min(-9, -8) = -9 min(-8, -9) = -9 max(-9, -6) = -6 max(-6, -9) = -6 min(-9, -6) = -9 min(-6, -9) = -9 max(-9, -4) = -4 max(-4, -9) = -4 min(-9, -4) = -9 min(-4, -9) = -9 max(-9, -2) = -2 max(-2, -9) = -2 min(-9, -2) = -9 min(-2, -9) = -9 max(-9, 0) = 0 max(0, -9) = 0 min(-9, 0) = -9 min(0, -9) = -9 max(-9, 2) = 2 max(2, -9) = 2 min(-9, 2) = -9 min(2, -9) = -9 max(-9, 4) = 4 max(4, -9) = 4 min(-9, 4) = -9 min(4, -9) = -9 max(-9, 6) = 6 max(6, -9) = 6 min(-9, 6) = -9 min(6, -9) = -9 max(-9, 8) = 8 max(8, -9) = 8 min(-9, 8) = -9 min(8, -9) = -9 max(-9, 10) = 10 max(10, -9) = 10 min(-9, 10) = -9 min(10, -9) = -9 max(-8, -10) = -8 max(-10, -8) = -8 min(-8, -10) = -10 min(-10, -8) = -10 max(-8, -8) = -8 max(-8, -8) = -8 min(-8, -8) = -8 min(-8, -8) = -8 max(-8, -6) = -6 max(-6, -8) = -6 min(-8, -6) = -8 min(-6, -8) = -8 max(-8, -4) = -4 max(-4, -8) = -4 min(-8, -4) = -8 min(-4, -8) = -8 max(-8, -2) = -2 max(-2, -8) = -2 min(-8, -2) = -8 min(-2, -8) = -8 max(-8, 0) = 0 max(0, -8) = 0 min(-8, 0) = -8 min(0, -8) = -8 max(-8, 2) = 2 max(2, -8) = 2 min(-8, 2) = -8 min(2, -8) = -8 max(-8, 4) = 4 max(4, -8) = 4 min(-8, 4) = -8 min(4, -8) = -8 max(-8, 6) = 6 max(6, -8) = 6 min(-8, 6) = -8 min(6, -8) = -8 max(-8, 8) = 8 max(8, -8) = 8 min(-8, 8) = -8 min(8, -8) = -8 max(-8, 10) = 10 max(10, -8) = 10 min(-8, 10) = -8 min(10, -8) = -8 max(-7, -10) = -7 max(-10, -7) = -7 min(-7, -10) = -10 min(-10, -7) = -10 max(-7, -8) = -7 max(-8, -7) = -7 min(-7, -8) = -8 min(-8, -7) = -8 max(-7, -6) = -6 max(-6, -7) = -6 min(-7, -6) = -7 min(-6, -7) = -7 max(-7, -4) = -4 max(-4, -7) = -4 min(-7, -4) = -7 min(-4, -7) = -7 max(-7, -2) = -2 max(-2, -7) = -2 min(-7, -2) = -7 min(-2, -7) = -7 max(-7, 0) = 0 max(0, -7) = 0 min(-7, 0) = -7 min(0, -7) = -7 max(-7, 2) = 2 max(2, -7) = 2 min(-7, 2) = -7 min(2, -7) = -7 max(-7, 4) = 4 max(4, -7) = 4 min(-7, 4) = -7 min(4, -7) = -7 max(-7, 6) = 6 max(6, -7) = 6 min(-7, 6) = -7 min(6, -7) = -7 max(-7, 8) = 8 max(8, -7) = 8 min(-7, 8) = -7 min(8, -7) = -7 max(-7, 10) = 10 max(10, -7) = 10 min(-7, 10) = -7 min(10, -7) = -7 max(-6, -10) = -6 max(-10, -6) = -6 min(-6, -10) = -10 min(-10, -6) = -10 max(-6, -8) = -6 max(-8, -6) = -6 min(-6, -8) = -8 min(-8, -6) = -8 max(-6, -6) = -6 max(-6, -6) = -6 min(-6, -6) = -6 min(-6, -6) = -6 max(-6, -4) = -4 max(-4, -6) = -4 min(-6, -4) = -6 min(-4, -6) = -6 max(-6, -2) = -2 max(-2, -6) = -2 min(-6, -2) = -6 min(-2, -6) = -6 max(-6, 0) = 0 max(0, -6) = 0 min(-6, 0) = -6 min(0, -6) = -6 max(-6, 2) = 2 max(2, -6) = 2 min(-6, 2) = -6 min(2, -6) = -6 max(-6, 4) = 4 max(4, -6) = 4 min(-6, 4) = -6 min(4, -6) = -6 max(-6, 6) = 6 max(6, -6) = 6 min(-6, 6) = -6 min(6, -6) = -6 max(-6, 8) = 8 max(8, -6) = 8 min(-6, 8) = -6 min(8, -6) = -6 max(-6, 10) = 10 max(10, -6) = 10 min(-6, 10) = -6 min(10, -6) = -6 max(-5, -10) = -5 max(-10, -5) = -5 min(-5, -10) = -10 min(-10, -5) = -10 max(-5, -8) = -5 max(-8, -5) = -5 min(-5, -8) = -8 min(-8, -5) = -8 max(-5, -6) = -5 max(-6, -5) = -5 min(-5, -6) = -6 min(-6, -5) = -6 max(-5, -4) = -4 max(-4, -5) = -4 min(-5, -4) = -5 min(-4, -5) = -5 max(-5, -2) = -2 max(-2, -5) = -2 min(-5, -2) = -5 min(-2, -5) = -5 max(-5, 0) = 0 max(0, -5) = 0 min(-5, 0) = -5 min(0, -5) = -5 max(-5, 2) = 2 max(2, -5) = 2 min(-5, 2) = -5 min(2, -5) = -5 max(-5, 4) = 4 max(4, -5) = 4 min(-5, 4) = -5 min(4, -5) = -5 max(-5, 6) = 6 max(6, -5) = 6 min(-5, 6) = -5 min(6, -5) = -5 max(-5, 8) = 8 max(8, -5) = 8 min(-5, 8) = -5 min(8, -5) = -5 max(-5, 10) = 10 max(10, -5) = 10 min(-5, 10) = -5 min(10, -5) = -5 max(-4, -10) = -4 max(-10, -4) = -4 min(-4, -10) = -10 min(-10, -4) = -10 max(-4, -8) = -4 max(-8, -4) = -4 min(-4, -8) = -8 min(-8, -4) = -8 max(-4, -6) = -4 max(-6, -4) = -4 min(-4, -6) = -6 min(-6, -4) = -6 max(-4, -4) = -4 max(-4, -4) = -4 min(-4, -4) = -4 min(-4, -4) = -4 max(-4, -2) = -2 max(-2, -4) = -2 min(-4, -2) = -4 min(-2, -4) = -4 max(-4, 0) = 0 max(0, -4) = 0 min(-4, 0) = -4 min(0, -4) = -4 max(-4, 2) = 2 max(2, -4) = 2 min(-4, 2) = -4 min(2, -4) = -4 max(-4, 4) = 4 max(4, -4) = 4 min(-4, 4) = -4 min(4, -4) = -4 max(-4, 6) = 6 max(6, -4) = 6 min(-4, 6) = -4 min(6, -4) = -4 max(-4, 8) = 8 max(8, -4) = 8 min(-4, 8) = -4 min(8, -4) = -4 max(-4, 10) = 10 max(10, -4) = 10 min(-4, 10) = -4 min(10, -4) = -4 max(-3, -10) = -3 max(-10, -3) = -3 min(-3, -10) = -10 min(-10, -3) = -10 max(-3, -8) = -3 max(-8, -3) = -3 min(-3, -8) = -8 min(-8, -3) = -8 max(-3, -6) = -3 max(-6, -3) = -3 min(-3, -6) = -6 min(-6, -3) = -6 max(-3, -4) = -3 max(-4, -3) = -3 min(-3, -4) = -4 min(-4, -3) = -4 max(-3, -2) = -2 max(-2, -3) = -2 min(-3, -2) = -3 min(-2, -3) = -3 max(-3, 0) = 0 max(0, -3) = 0 min(-3, 0) = -3 min(0, -3) = -3 max(-3, 2) = 2 max(2, -3) = 2 min(-3, 2) = -3 min(2, -3) = -3 max(-3, 4) = 4 max(4, -3) = 4 min(-3, 4) = -3 min(4, -3) = -3 max(-3, 6) = 6 max(6, -3) = 6 min(-3, 6) = -3 min(6, -3) = -3 max(-3, 8) = 8 max(8, -3) = 8 min(-3, 8) = -3 min(8, -3) = -3 max(-3, 10) = 10 max(10, -3) = 10 min(-3, 10) = -3 min(10, -3) = -3 max(-2, -10) = -2 max(-10, -2) = -2 min(-2, -10) = -10 min(-10, -2) = -10 max(-2, -8) = -2 max(-8, -2) = -2 min(-2, -8) = -8 min(-8, -2) = -8 max(-2, -6) = -2 max(-6, -2) = -2 min(-2, -6) = -6 min(-6, -2) = -6 max(-2, -4) = -2 max(-4, -2) = -2 min(-2, -4) = -4 min(-4, -2) = -4 max(-2, -2) = -2 max(-2, -2) = -2 min(-2, -2) = -2 min(-2, -2) = -2 max(-2, 0) = 0 max(0, -2) = 0 min(-2, 0) = -2 min(0, -2) = -2 max(-2, 2) = 2 max(2, -2) = 2 min(-2, 2) = -2 min(2, -2) = -2 max(-2, 4) = 4 max(4, -2) = 4 min(-2, 4) = -2 min(4, -2) = -2 max(-2, 6) = 6 max(6, -2) = 6 min(-2, 6) = -2 min(6, -2) = -2 max(-2, 8) = 8 max(8, -2) = 8 min(-2, 8) = -2 min(8, -2) = -2 max(-2, 10) = 10 max(10, -2) = 10 min(-2, 10) = -2 min(10, -2) = -2 max(-1, -10) = -1 max(-10, -1) = -1 min(-1, -10) = -10 min(-10, -1) = -10 max(-1, -8) = -1 max(-8, -1) = -1 min(-1, -8) = -8 min(-8, -1) = -8 max(-1, -6) = -1 max(-6, -1) = -1 min(-1, -6) = -6 min(-6, -1) = -6 max(-1, -4) = -1 max(-4, -1) = -1 min(-1, -4) = -4 min(-4, -1) = -4 max(-1, -2) = -1 max(-2, -1) = -1 min(-1, -2) = -2 min(-2, -1) = -2 max(-1, 0) = 0 max(0, -1) = 0 min(-1, 0) = -1 min(0, -1) = -1 max(-1, 2) = 2 max(2, -1) = 2 min(-1, 2) = -1 min(2, -1) = -1 max(-1, 4) = 4 max(4, -1) = 4 min(-1, 4) = -1 min(4, -1) = -1 max(-1, 6) = 6 max(6, -1) = 6 min(-1, 6) = -1 min(6, -1) = -1 max(-1, 8) = 8 max(8, -1) = 8 min(-1, 8) = -1 min(8, -1) = -1 max(-1, 10) = 10 max(10, -1) = 10 min(-1, 10) = -1 min(10, -1) = -1 max(0, -10) = 0 max(-10, 0) = 0 min(0, -10) = -10 min(-10, 0) = -10 max(0, -8) = 0 max(-8, 0) = 0 min(0, -8) = -8 min(-8, 0) = -8 max(0, -6) = 0 max(-6, 0) = 0 min(0, -6) = -6 min(-6, 0) = -6 max(0, -4) = 0 max(-4, 0) = 0 min(0, -4) = -4 min(-4, 0) = -4 max(0, -2) = 0 max(-2, 0) = 0 min(0, -2) = -2 min(-2, 0) = -2 max(0, 0) = 0 max(0, 0) = 0 min(0, 0) = 0 min(0, 0) = 0 max(0, 2) = 2 max(2, 0) = 2 min(0, 2) = 0 min(2, 0) = 0 max(0, 4) = 4 max(4, 0) = 4 min(0, 4) = 0 min(4, 0) = 0 max(0, 6) = 6 max(6, 0) = 6 min(0, 6) = 0 min(6, 0) = 0 max(0, 8) = 8 max(8, 0) = 8 min(0, 8) = 0 min(8, 0) = 0 max(0, 10) = 10 max(10, 0) = 10 min(0, 10) = 0 min(10, 0) = 0 max(1, -10) = 1 max(-10, 1) = 1 min(1, -10) = -10 min(-10, 1) = -10 max(1, -8) = 1 max(-8, 1) = 1 min(1, -8) = -8 min(-8, 1) = -8 max(1, -6) = 1 max(-6, 1) = 1 min(1, -6) = -6 min(-6, 1) = -6 max(1, -4) = 1 max(-4, 1) = 1 min(1, -4) = -4 min(-4, 1) = -4 max(1, -2) = 1 max(-2, 1) = 1 min(1, -2) = -2 min(-2, 1) = -2 max(1, 0) = 1 max(0, 1) = 1 min(1, 0) = 0 min(0, 1) = 0 max(1, 2) = 2 max(2, 1) = 2 min(1, 2) = 1 min(2, 1) = 1 max(1, 4) = 4 max(4, 1) = 4 min(1, 4) = 1 min(4, 1) = 1 max(1, 6) = 6 max(6, 1) = 6 min(1, 6) = 1 min(6, 1) = 1 max(1, 8) = 8 max(8, 1) = 8 min(1, 8) = 1 min(8, 1) = 1 max(1, 10) = 10 max(10, 1) = 10 min(1, 10) = 1 min(10, 1) = 1 max(2, -10) = 2 max(-10, 2) = 2 min(2, -10) = -10 min(-10, 2) = -10 max(2, -8) = 2 max(-8, 2) = 2 min(2, -8) = -8 min(-8, 2) = -8 max(2, -6) = 2 max(-6, 2) = 2 min(2, -6) = -6 min(-6, 2) = -6 max(2, -4) = 2 max(-4, 2) = 2 min(2, -4) = -4 min(-4, 2) = -4 max(2, -2) = 2 max(-2, 2) = 2 min(2, -2) = -2 min(-2, 2) = -2 max(2, 0) = 2 max(0, 2) = 2 min(2, 0) = 0 min(0, 2) = 0 max(2, 2) = 2 max(2, 2) = 2 min(2, 2) = 2 min(2, 2) = 2 max(2, 4) = 4 max(4, 2) = 4 min(2, 4) = 2 min(4, 2) = 2 max(2, 6) = 6 max(6, 2) = 6 min(2, 6) = 2 min(6, 2) = 2 max(2, 8) = 8 max(8, 2) = 8 min(2, 8) = 2 min(8, 2) = 2 max(2, 10) = 10 max(10, 2) = 10 min(2, 10) = 2 min(10, 2) = 2 max(3, -10) = 3 max(-10, 3) = 3 min(3, -10) = -10 min(-10, 3) = -10 max(3, -8) = 3 max(-8, 3) = 3 min(3, -8) = -8 min(-8, 3) = -8 max(3, -6) = 3 max(-6, 3) = 3 min(3, -6) = -6 min(-6, 3) = -6 max(3, -4) = 3 max(-4, 3) = 3 min(3, -4) = -4 min(-4, 3) = -4 max(3, -2) = 3 max(-2, 3) = 3 min(3, -2) = -2 min(-2, 3) = -2 max(3, 0) = 3 max(0, 3) = 3 min(3, 0) = 0 min(0, 3) = 0 max(3, 2) = 3 max(2, 3) = 3 min(3, 2) = 2 min(2, 3) = 2 max(3, 4) = 4 max(4, 3) = 4 min(3, 4) = 3 min(4, 3) = 3 max(3, 6) = 6 max(6, 3) = 6 min(3, 6) = 3 min(6, 3) = 3 max(3, 8) = 8 max(8, 3) = 8 min(3, 8) = 3 min(8, 3) = 3 max(3, 10) = 10 max(10, 3) = 10 min(3, 10) = 3 min(10, 3) = 3 max(4, -10) = 4 max(-10, 4) = 4 min(4, -10) = -10 min(-10, 4) = -10 max(4, -8) = 4 max(-8, 4) = 4 min(4, -8) = -8 min(-8, 4) = -8 max(4, -6) = 4 max(-6, 4) = 4 min(4, -6) = -6 min(-6, 4) = -6 max(4, -4) = 4 max(-4, 4) = 4 min(4, -4) = -4 min(-4, 4) = -4 max(4, -2) = 4 max(-2, 4) = 4 min(4, -2) = -2 min(-2, 4) = -2 max(4, 0) = 4 max(0, 4) = 4 min(4, 0) = 0 min(0, 4) = 0 max(4, 2) = 4 max(2, 4) = 4 min(4, 2) = 2 min(2, 4) = 2 max(4, 4) = 4 max(4, 4) = 4 min(4, 4) = 4 min(4, 4) = 4 max(4, 6) = 6 max(6, 4) = 6 min(4, 6) = 4 min(6, 4) = 4 max(4, 8) = 8 max(8, 4) = 8 min(4, 8) = 4 min(8, 4) = 4 max(4, 10) = 10 max(10, 4) = 10 min(4, 10) = 4 min(10, 4) = 4 max(5, -10) = 5 max(-10, 5) = 5 min(5, -10) = -10 min(-10, 5) = -10 max(5, -8) = 5 max(-8, 5) = 5 min(5, -8) = -8 min(-8, 5) = -8 max(5, -6) = 5 max(-6, 5) = 5 min(5, -6) = -6 min(-6, 5) = -6 max(5, -4) = 5 max(-4, 5) = 5 min(5, -4) = -4 min(-4, 5) = -4 max(5, -2) = 5 max(-2, 5) = 5 min(5, -2) = -2 min(-2, 5) = -2 max(5, 0) = 5 max(0, 5) = 5 min(5, 0) = 0 min(0, 5) = 0 max(5, 2) = 5 max(2, 5) = 5 min(5, 2) = 2 min(2, 5) = 2 max(5, 4) = 5 max(4, 5) = 5 min(5, 4) = 4 min(4, 5) = 4 max(5, 6) = 6 max(6, 5) = 6 min(5, 6) = 5 min(6, 5) = 5 max(5, 8) = 8 max(8, 5) = 8 min(5, 8) = 5 min(8, 5) = 5 max(5, 10) = 10 max(10, 5) = 10 min(5, 10) = 5 min(10, 5) = 5 max(6, -10) = 6 max(-10, 6) = 6 min(6, -10) = -10 min(-10, 6) = -10 max(6, -8) = 6 max(-8, 6) = 6 min(6, -8) = -8 min(-8, 6) = -8 max(6, -6) = 6 max(-6, 6) = 6 min(6, -6) = -6 min(-6, 6) = -6 max(6, -4) = 6 max(-4, 6) = 6 min(6, -4) = -4 min(-4, 6) = -4 max(6, -2) = 6 max(-2, 6) = 6 min(6, -2) = -2 min(-2, 6) = -2 max(6, 0) = 6 max(0, 6) = 6 min(6, 0) = 0 min(0, 6) = 0 max(6, 2) = 6 max(2, 6) = 6 min(6, 2) = 2 min(2, 6) = 2 max(6, 4) = 6 max(4, 6) = 6 min(6, 4) = 4 min(4, 6) = 4 max(6, 6) = 6 max(6, 6) = 6 min(6, 6) = 6 min(6, 6) = 6 max(6, 8) = 8 max(8, 6) = 8 min(6, 8) = 6 min(8, 6) = 6 max(6, 10) = 10 max(10, 6) = 10 min(6, 10) = 6 min(10, 6) = 6 max(7, -10) = 7 max(-10, 7) = 7 min(7, -10) = -10 min(-10, 7) = -10 max(7, -8) = 7 max(-8, 7) = 7 min(7, -8) = -8 min(-8, 7) = -8 max(7, -6) = 7 max(-6, 7) = 7 min(7, -6) = -6 min(-6, 7) = -6 max(7, -4) = 7 max(-4, 7) = 7 min(7, -4) = -4 min(-4, 7) = -4 max(7, -2) = 7 max(-2, 7) = 7 min(7, -2) = -2 min(-2, 7) = -2 max(7, 0) = 7 max(0, 7) = 7 min(7, 0) = 0 min(0, 7) = 0 max(7, 2) = 7 max(2, 7) = 7 min(7, 2) = 2 min(2, 7) = 2 max(7, 4) = 7 max(4, 7) = 7 min(7, 4) = 4 min(4, 7) = 4 max(7, 6) = 7 max(6, 7) = 7 min(7, 6) = 6 min(6, 7) = 6 max(7, 8) = 8 max(8, 7) = 8 min(7, 8) = 7 min(8, 7) = 7 max(7, 10) = 10 max(10, 7) = 10 min(7, 10) = 7 min(10, 7) = 7 max(8, -10) = 8 max(-10, 8) = 8 min(8, -10) = -10 min(-10, 8) = -10 max(8, -8) = 8 max(-8, 8) = 8 min(8, -8) = -8 min(-8, 8) = -8 max(8, -6) = 8 max(-6, 8) = 8 min(8, -6) = -6 min(-6, 8) = -6 max(8, -4) = 8 max(-4, 8) = 8 min(8, -4) = -4 min(-4, 8) = -4 max(8, -2) = 8 max(-2, 8) = 8 min(8, -2) = -2 min(-2, 8) = -2 max(8, 0) = 8 max(0, 8) = 8 min(8, 0) = 0 min(0, 8) = 0 max(8, 2) = 8 max(2, 8) = 8 min(8, 2) = 2 min(2, 8) = 2 max(8, 4) = 8 max(4, 8) = 8 min(8, 4) = 4 min(4, 8) = 4 max(8, 6) = 8 max(6, 8) = 8 min(8, 6) = 6 min(6, 8) = 6 max(8, 8) = 8 max(8, 8) = 8 min(8, 8) = 8 min(8, 8) = 8 max(8, 10) = 10 max(10, 8) = 10 min(8, 10) = 8 min(10, 8) = 8 max(9, -10) = 9 max(-10, 9) = 9 min(9, -10) = -10 min(-10, 9) = -10 max(9, -8) = 9 max(-8, 9) = 9 min(9, -8) = -8 min(-8, 9) = -8 max(9, -6) = 9 max(-6, 9) = 9 min(9, -6) = -6 min(-6, 9) = -6 max(9, -4) = 9 max(-4, 9) = 9 min(9, -4) = -4 min(-4, 9) = -4 max(9, -2) = 9 max(-2, 9) = 9 min(9, -2) = -2 min(-2, 9) = -2 max(9, 0) = 9 max(0, 9) = 9 min(9, 0) = 0 min(0, 9) = 0 max(9, 2) = 9 max(2, 9) = 9 min(9, 2) = 2 min(2, 9) = 2 max(9, 4) = 9 max(4, 9) = 9 min(9, 4) = 4 min(4, 9) = 4 max(9, 6) = 9 max(6, 9) = 9 min(9, 6) = 6 min(6, 9) = 6 max(9, 8) = 9 max(8, 9) = 9 min(9, 8) = 8 min(8, 9) = 8 max(9, 10) = 10 max(10, 9) = 10 min(9, 10) = 9 min(10, 9) = 9 max(10, -10) = 10 max(-10, 10) = 10 min(10, -10) = -10 min(-10, 10) = -10 max(10, -8) = 10 max(-8, 10) = 10 min(10, -8) = -8 min(-8, 10) = -8 max(10, -6) = 10 max(-6, 10) = 10 min(10, -6) = -6 min(-6, 10) = -6 max(10, -4) = 10 max(-4, 10) = 10 min(10, -4) = -4 min(-4, 10) = -4 max(10, -2) = 10 max(-2, 10) = 10 min(10, -2) = -2 min(-2, 10) = -2 max(10, 0) = 10 max(0, 10) = 10 min(10, 0) = 0 min(0, 10) = 0 max(10, 2) = 10 max(2, 10) = 10 min(10, 2) = 2 min(2, 10) = 2 max(10, 4) = 10 max(4, 10) = 10 min(10, 4) = 4 min(4, 10) = 4 max(10, 6) = 10 max(6, 10) = 10 min(10, 6) = 6 min(6, 10) = 6 max(10, 8) = 10 max(8, 10) = 10 min(10, 8) = 8 min(8, 10) = 8 max(10, 10) = 10 max(10, 10) = 10 min(10, 10) = 10 min(10, 10) = 10 clearsilver-0.10.5/cs/test_cgi_escape.cs0000644001211700116100000000372610465716057015124 00000000000000 <?cs var:Title ?> default escape explicit escape implicit: explicit escape: uvar: implicit_slice: slice_explicit_escape: explicit_escape_slice: non-html output: get_var: get_var_inside_url_escape: get_var_inside_url_escape_with_explicit_escape: get_var_inside_none_escape: get_var_inside_none_escape_with_explicit_url_escape: nested ifs Calling get_var(UrlArg) from within 'escape: "html"'
--> Including test_escape.cs:
--- ---- escape level 1 escape level 2 clearsilver-0.10.5/cs/test_chuck.cs0000644001211700116100000000105510261037510014110 00000000000000" + val + "" ?> Biz.Address2 = Biz.Address3 = clearsilver-0.10.5/cs/test_chuck.cs.gold0000644001211700116100000000016510616225375015051 00000000000000Parsing test_chuck.cs Biz.Address2 = addr Biz.Address3 = clearsilver-0.10.5/cs/test_comma.cs0000644001211700116100000000030410366307121014107 00000000000000 Comma tests, evalute both but pass right most as expression result 4: also, "do nothing" lparen operator 4: 2: 3: clearsilver-0.10.5/cs/test_comma.cs.gold0000644001211700116100000000022510616225375015045 00000000000000Parsing test_comma.cs Comma tests, evalute both but pass right most as expression result 4: 4 also, "do nothing" lparen operator 4: 4 2: 2 3: 3 clearsilver-0.10.5/cs/test_crc.cs0000644001211700116100000000017010616225120013557 00000000000000 clearsilver-0.10.5/cs/test_crc.cs.gold0000644001211700116100000000006510616225375014522 00000000000000Parsing test_crc.cs 419156592 1357503972 -2128917020 clearsilver-0.10.5/cs/test_each_array.cs0000644001211700116100000000010410261037510015103 00000000000000 clearsilver-0.10.5/cs/test_each_array.cs.gold0000644001211700116100000000007510616225375016052 00000000000000Parsing test_each_array.cs zero one two three clearsilver-0.10.5/cs/test_escape.cs0000644001211700116100000000341210465716057014272 00000000000000escape: not used UrlArg: BlahJs: Title: escape: none UrlArg: BlahJs: Title: escape: html UrlArg: BlahJs: Title: escape: js UrlArg: BlahJs: Title: escape: url UrlArg: BlahJs: Title: Nested escaping: html The internal calls should take precedence url -> UrlArg: js -> BlahJs: html -> Title: Defining the macro echo_all inside of a "html" escape. not used: none: url: js: html: Calling echo_all() macro: Calling echo_all() macro from within "html": Calling echo_all() macro from within "js": Calling echo_all() macro from within "url": clearsilver-0.10.5/cs/test_escape.cs.gold0000644001211700116100000000757510616225375015230 00000000000000Parsing test_escape.cs escape: not used UrlArg: Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? BlahJs: quote ' backslash \ semicolon ; end tag Title: escape: none UrlArg: Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? BlahJs: quote ' backslash \ semicolon ; end tag Title: escape: html UrlArg: Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? BlahJs: quote ' backslash \ semicolon ; end tag </script> Title: </title><script>alert(1)</script> escape: js UrlArg: Secret Password~!@#$%^\x26*()+=-_|\x5C[]{}:\x22\x3B\x27\x3C\x3E,.? BlahJs: quote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E Title: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3E escape: url UrlArg: Secret+Password%7E!%40%23%24%25%5E%26*()%2B%3D-_%7C%5C%5B%5D%7B%7D%3A%22%3B%27%3C%3E%2C.%3F BlahJs: quote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E Title: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3E Nested escaping: html The internal calls should take precedence url -> UrlArg: Secret+Password%7E!%40%23%24%25%5E%26*()%2B%3D-_%7C%5C%5B%5D%7B%7D%3A%22%3B%27%3C%3E%2C.%3F js -> BlahJs: quote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html -> Title: </title><script>alert(1)</script> Defining the macro echo_all inside of a "html" escape. Calling echo_all() macro: not used: quote ' backslash \ semicolon ; end tag none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> Calling echo_all() macro from within "html": not used: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> Calling echo_all() macro from within "js": not used: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> Calling echo_all() macro from within "url": not used: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E none: quote ' backslash \ semicolon ; end tag url: %3C%2Ftitle%3E%3Cscript%3Ealert(1)%3C%2Fscript%3Equote+%27+backslash+%5C+semicolon+%3B+end+tag+%3C%2Fscript%3E js: \x3C\x2Ftitle\x3E\x3Cscript\x3Ealert(1)\x3C\x2Fscript\x3Equote \x27 backslash \x5C semicolon \x3B end tag \x3C\x2Fscript\x3E html: </title><script>alert(1)</script>quote ' backslash \ semicolon ; end tag </script> clearsilver-0.10.5/cs/test_exists.cs0000644001211700116100000000015310261037510014330 00000000000000array exists test PASS ERROR clearsilver-0.10.5/cs/test_first_last.cs0000644001211700116100000000134010305645042015166 00000000000000 is_first: is_last: is_first: is_first: -> never is_last: is_last: -> never Only one, so should be first and last is_first: is_last: Testing loop is_first: is_first: -> never is_last: is_last: -> never clearsilver-0.10.5/cs/test_first_last.cs.gold0000644001211700116100000000314010616225375016122 00000000000000Parsing test_first_last.cs 9 is_first: 1 is_last: 0 14 is_first: 0 is_last: 1 0 is_first: 1 is_first: 0 -> never is_last: 0 is_last: 0 -> never 1 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 2 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 3 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 4 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 5 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 6 is_first: 0 is_first: 0 -> never is_last: 1 is_last: 0 -> never Only one, so should be first and last is_first: 1 is_last: 1 Testing loop 0 is_first: 1 is_first: 0 -> never is_last: 0 is_last: 0 -> never 5 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 10 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 15 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 20 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 25 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 30 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 35 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 40 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 45 is_first: 0 is_first: 0 -> never is_last: 0 is_last: 0 -> never 50 is_first: 0 is_first: 0 -> never is_last: 1 is_last: 0 -> never clearsilver-0.10.5/cs/test_func.cs0000644001211700116100000000120210370250052013737 00000000000000testing func calls Testing register strfunc testing passing expressions to builtins 25: 15: 6: 25: 4: Baz: oba: first/last only run on local vars, which can't be created by expressions clearsilver-0.10.5/cs/test_func.cs.gold0000644001211700116100000000047010616225375014706 00000000000000Parsing test_func.cs testing func calls Testing register strfunc worn out fooworn out 2 4 testing passing expressions to builtins 5 3 1 1 3 5 7 9 11 13 15 25: 25 15: 15 6: 6 25: 25 4: 4 Baz: Baz oba: oba first/last only run on local vars, which can't be created by expressions clearsilver-0.10.5/cs/test_iter.cs0000644001211700116100000000046110261037510013756 00000000000000 #Query.start && #count < #next ?> clearsilver-0.10.5/cs/test_iter.cs.gold0000644001211700116100000000067110616225375014721 00000000000000Parsing test_iter.cs 11 12 13 14 15 16 17 18 19 clearsilver-0.10.5/cs/test_joo.cs0000644001211700116100000001030410261037510013577 00000000000000Testing Empty String and empty var Empty has no value assigned (ie, empty), Foo has a value, NotExist doesn't exist Some of these tests are pretty silly ---------------------------------------------------------------------------------- Testing == '' [1] Empty == '' PASS FAIL - empty string should equal empty string [1] [2] Foo == '' FAIL - existing var shouldn't equal empty string [2] PASS [3] NotExist == '' FAIL - non-existing should be NULL, not empty string [3] PASS Testing != '' [4] Empty != '' FAIL - Empty var should equal empty string [4] PASS [5] Foo != '' PASS FAIL - [5] [6] NotExist != '' PASS - Non existing var doesn't equal empty string FAIL - [6] Testing ? [7] ?Empty PASS FAIL - [7] [8] ?Foo PASS FAIL - [8] [9] ?NotExist FAIL - non existing var shouldn't exist [9] PASS Testing ! [10] !Empty PASS FAIL - [10] [11] !Foo FAIL - existing string shouldn't evaluate false [11] PASS [12] !NotExist PASS FAIL - [12] Testing !? [13] !?Empty FAIL - empty string shouldn't evaluate non-existing [13] PASS [14] !?Foo FAIL - non-empty string shouldn't evaluate non-existing [14] PASS [15] !?NotExist PASS FAIL - [15] Testing ?! - Existance only works on a var, otherwise always returns true, so ?! is always true [16] ?!Empty PASS FAIL - [16] [17] ?!Foo PASS FAIL - [17] [18] ?!NotExist PASS FAIL - [18] Testing ? and == '' - boolean vs. equality? um... boolean is a number, so these are numeric evals, and empty string is 0 [19] ?Empty == '' FAIL - IF boolean true equals empty [19] PASS - ELSE boolean true doesn't equal empty (1 != 0) [20] ?Foo == '' FAIL - IF boolean true equals empty [20] PASS - ELSE boolean true doesn't equal empty (1 != 0) [21] ?NotExist == '' PASS - IF boolean false equals empty (0 == 0) [22] FAIL - ELSE boolean false doesn't equal empty [22] Testing ? and != '' - boolean vs. in-equality? um... [23] ?Empty != '' PASS - IF boolean true not equal empty (1 != 0) FAIL - ELSE boolean true equals empty [23] [24] ?Foo != '' PASS - IF boolean true not equal empty (1 != 0) FAIL - ELSE boolean true equals empty [24] [25] ?NotExist != '' FAIL - IF boolean false not equal empty [25] PASS - ELSE boolean false equals empty (0 == 0) Testing !? and == '' - all boolean true equals empty [26] !?Empty == '' PASS - IF boolean true equals empty FAIL - ELSE boolean true doesn't equal empty [26] [27] !?Foo == '' PASS - IF boolean true equals empty FAIL - ELSE boolean true doesn't equal empty [27] [28] !?NotExist == '' FAIL - IF boolean true equals empty [28] PASS - ELSE boolean true doesn't equal empty Testing !? and != '' [29] !?Empty != '' FAIL - IF boolean true not equal empty [29] PASS - ELSE boolean true equals empty [30] !?Foo != '' FAIL - IF boolean true not equal empty [30] PASS - ELSE boolean true equals empty [31] !?NotExist != '' PASS - IF boolean true not equal empty FAIL - ELSE boolean true equals empty [31] clearsilver-0.10.5/cs/test_joo.cs.gold0000644001211700116100000000353510616225375014547 00000000000000Parsing test_joo.cs Testing Empty String and empty var Empty has no value assigned (ie, empty), Foo has a value, NotExist doesn't exist Some of these tests are pretty silly ---------------------------------------------------------------------------------- Testing == '' [1] Empty == '' PASS [2] Foo == '' PASS [3] NotExist == '' PASS Testing != '' [4] Empty != '' PASS [5] Foo != '' PASS [6] NotExist != '' PASS - Non existing var doesn't equal empty string Testing ? [7] ?Empty PASS [8] ?Foo PASS [9] ?NotExist PASS Testing ! [10] !Empty PASS [11] !Foo PASS [12] !NotExist PASS Testing !? [13] !?Empty PASS [14] !?Foo PASS [15] !?NotExist PASS Testing ?! - Existance only works on a var, otherwise always returns true, so ?! is always true [16] ?!Empty PASS [17] ?!Foo PASS [18] ?!NotExist PASS Testing ? and == '' - boolean vs. equality? um... boolean is a number, so these are numeric evals, and empty string is 0 [19] ?Empty == '' PASS - ELSE boolean true doesn't equal empty (1 != 0) [20] ?Foo == '' PASS - ELSE boolean true doesn't equal empty (1 != 0) [21] ?NotExist == '' PASS - IF boolean false equals empty (0 == 0) Testing ? and != '' - boolean vs. in-equality? um... [23] ?Empty != '' PASS - IF boolean true not equal empty (1 != 0) [24] ?Foo != '' PASS - IF boolean true not equal empty (1 != 0) [25] ?NotExist != '' PASS - ELSE boolean false equals empty (0 == 0) Testing !? and == '' - all boolean true equals empty [26] !?Empty == '' PASS - IF boolean true equals empty [27] !?Foo == '' PASS - IF boolean true equals empty [28] !?NotExist == '' PASS - ELSE boolean true doesn't equal empty Testing !? and != '' [29] !?Empty != '' PASS - ELSE boolean true equals empty [30] !?Foo != '' PASS - ELSE boolean true equals empty [31] !?NotExist != '' PASS - IF boolean true not equal empty clearsilver-0.10.5/cs/test_macro_set.cs0000644001211700116100000000105310366266755015012 00000000000000 Testing "pass by reference" to macro calls so they can "return" data Testing non-existant var Testing non-existant var sub var Testing non-existant sub var Testing existant var clearsilver-0.10.5/cs/test_macro_set.cs.gold0000644001211700116100000000047210616225375015731 00000000000000Parsing test_macro_set.cs Testing "pass by reference" to macro calls so they can "return" data Testing non-existant var style='width:100px;' Testing non-existant var sub var style='width:300px;' Testing non-existant sub var style='width:400px;' Testing existant var style='width:200px;' clearsilver-0.10.5/cs/test_name.cs0000644001211700116100000000014610261037510013733 00000000000000 clearsilver-0.10.5/cs/test_name.cs.gold0000644001211700116100000000006110616225375014667 00000000000000Parsing test_name.cs Foo 0 1 2 3 clearsilver-0.10.5/cs/test_numbers.cs0000644001211700116100000000172610261037510014473 00000000000000 CORRECT: -1 == -1 ERROR: -1 should equal -1 CORRECT: -1 is boolean true ERROR : -1 should be boolean true CORRECT: #-1 is boolean true ERROR : #-1 should be boolean true ERROR: 0 should be boolean false CORRECT: 0 is boolean false ERROR: 00 should be boolean false CORRECT: 00 is boolean false CORRECT: 0x15 (hex) == 21 ERROR: 0x15 (hex) should equal 21 CORRECT: 0x15 is boolean true ERROR: 0x15 should be boolean true CORRECT: (3*2)+4 does equal 10 ERROR: (3*2)+4 should equal 10 CORRECT: 0 + 2 == 2 ERROR: 0 + 2 should equal 2 clearsilver-0.10.5/cs/test_numbers.cs.gold0000644001211700116100000000047010616225375015426 00000000000000Parsing test_numbers.cs -1 CORRECT: -1 == -1 CORRECT: -1 is boolean true CORRECT: #-1 is boolean true CORRECT: 0 is boolean false CORRECT: 00 is boolean false CORRECT: 0x15 (hex) == 21 CORRECT: 0x15 is boolean true CORRECT: (3*2)+4 does equal 10 CORRECT: 0 + 2 == 2 clearsilver-0.10.5/cs/test_paren.cs0000644001211700116100000000012410261037510014114 00000000000000 VALUE:: clearsilver-0.10.5/cs/test_paren.cs.gold0000644001211700116100000000005110616225375015053 00000000000000Parsing test_paren.cs VALUE:HELLO(): clearsilver-0.10.5/cs/test_splice.cs0000644001211700116100000000034310261037510014271 00000000000000 Check end of string slice: clearsilver-0.10.5/cs/test_splice.cs.gold0000644001211700116100000000102110616225375015223 00000000000000Parsing test_splice.cs Worn Out Worn Out Worn Out Worn Out Worn Ou Worn O Worn Worn Wor Wo W orn Out orn Out orn Out orn Ou orn O orn orn or o rn Out rn Out rn Out rn Ou rn O rn rn r n Out n Out n Out n Ou n O n n Out Out Out Ou O Out Out Out Ou O ut ut ut u t t t Check end of string slice: n Ou n Out clearsilver-0.10.5/cs/test_str_find.cs0000644001211700116100000000112410515537543014635 00000000000000 clearsilver-0.10.5/cs/test_str_find.cs.gold0000644001211700116100000000042110515537543015560 00000000000000Parsing test_str_find.cs string.find("String1", "ring") 2 string.find("String1", "1") 6 string.find("String1", "S") 0 string.find("String1", "k") -1 Foo = "TheString2" string.find(Foo, "Str") 3 string.find(Foo, 1+1) 9 clearsilver-0.10.5/cs/test_tag.cs0000644001211700116100000000010510261037510013561 00000000000000 clearsilver-0.10.5/cs/test_tag.cs.gold0000644001211700116100000000011610616225375014523 00000000000000Parsing test_tag.cs 0 1 2 clearsilver-0.10.5/cs/test_tag.hdf0000644001211700116100000000002710261037510013720 00000000000000Config.TagStart = int1 clearsilver-0.10.5/cs/test_trak1.cs0000644001211700116100000000035310261037510014035 00000000000000 matched clearsilver-0.10.5/cs/test_trak1.cs.gold0000644001211700116100000000004010616225375014766 00000000000000Parsing test_trak1.cs 2 clearsilver-0.10.5/cs/test_url_validate.cs0000644001211700116100000000171710645301257015503 00000000000000The following urls should be allowed unmodified: = = = = = = = = = This URL should be html escaped: = These URLs should be changed to # = = = = = clearsilver-0.10.5/cs/test_url_validate.hdf0000644001211700116100000000076610645301257015642 00000000000000BlahUrl = http://www.google.com SslUrl = https://www.google.com FtpUrl = ftp://www.google.com/a MailUrl = mailto:tester@google.com JsUrl = javascript:www.google.com DataUrl = data:text/html;base64,PHNjcmlwdD5hbGVydCgncmZjMjM5NyBpcyBzY2FyeScpPC9zY3JpcHQ+ AbsUrl = /mail/ AbsUrl2 = / RelUrl = mail/google.x HtmlUrl = http://www.google.com//good.x ColonUrl = relative/path:name ColonUrlTwo = /mail/path:name InvalidUrl = mail:80 InvalidUrl2 = www.google.com:80 ShortUrl = m:x clearsilver-0.10.5/cs/test_uvar.cs0000644001211700116100000000046710465716057014016 00000000000000 clearsilver-0.10.5/cs/test_uvar.cs.gold0000644001211700116100000000122610616225375014730 00000000000000Parsing test_uvar.cs quote ' backslash \ semicolon ; end tag Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? quote ' backslash \ semicolon ; end tag Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? quote ' backslash \ semicolon ; end tag Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? quote ' backslash \ semicolon ; end tag Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? quote ' backslash \ semicolon ; end tag Secret Password~!@#$%^&*()+=-_|\[]{}:";'<>,.? clearsilver-0.10.5/cs/test_var.cs0000644001211700116100000000002110337002743013577 00000000000000 clearsilver-0.10.5/cs/test_var.cs.gold0000644001211700116100000000003010616225375014533 00000000000000Parsing test_var.cs wow clearsilver-0.10.5/cs/test_with.cs0000644001211700116100000000017410261037510013767 00000000000000 - clearsilver-0.10.5/cs/test_with.cs.gold0000644001211700116100000000023610616225375014726 00000000000000Parsing test_with.cs 0 - Mon 1 - Tues 2 - Wed 3 - Thur 4 - Fri 5 - Sat 6 - Sun clearsilver-0.10.5/cgi/0000755001211700116100000000000010645505044011651 500000000000000clearsilver-0.10.5/cgi/Makefile0000644001211700116100000000255410524726471013244 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk CGI_LIB = $(LIB_DIR)libneo_cgi.a CGI_SRC = cgiwrap.c cgi.c html.c date.c rfc2388.c CGI_OBJ = $(CGI_SRC:%.c=%.o) STATIC_EXE = cs_static.cgi STATIC_SRC = static.c STATIC_OBJ = $(STATIC_SRC:%.c=%.o) STATIC_CSO = $(STATIC_EXE:%.cgi=%.cso) CGICSTEST_EXE = cgi_cstest CGICSTEST_SRC = cgi_cstest.c CGICSTEST_OBJ = $(CGICSTEST_SRC:%.c=%.o) DLIBS += -lneo_cgi -lneo_cs -lneo_utl # -lefence TARGETS = $(CGI_LIB) $(STATIC_EXE) $(STATIC_CSO) $(CGICSTEST_EXE) all: $(TARGETS) $(CGI_LIB): $(CGI_OBJ) $(AR) $@ $(CGI_OBJ) $(RANLIB) $@ $(STATIC_EXE): $(STATIC_OBJ) $(DEP_LIBS) $(LD) $@ $(STATIC_OBJ) $(LDFLAGS) $(DLIBS) $(LIBS) $(STATIC_CSO): $(STATIC_OBJ) $(DEP_LIBS) $(LDSHARED) -o $@ $(STATIC_OBJ) $(LDFLAGS) $(DLIBS) $(LIBS) $(CGICSTEST_EXE): $(CGICSTEST_OBJ) $(DEP_LIBS) $(LD) $@ $(CGICSTEST_OBJ) $(LDFLAGS) $(DLIBS) $(LIBS) install: all $(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(cs_includedir)/cgi $(INSTALL) -m 644 cgi.h $(DESTDIR)$(cs_includedir)/cgi $(INSTALL) -m 644 cgiwrap.h $(DESTDIR)$(cs_includedir)/cgi $(INSTALL) -m 644 date.h $(DESTDIR)$(cs_includedir)/cgi $(INSTALL) -m 644 html.h $(DESTDIR)$(cs_includedir)/cgi $(INSTALL) -m 644 $(CGI_LIB) $(DESTDIR)$(libdir) $(INSTALL) $(STATIC_EXE) $(DESTDIR)$(bindir) clean: $(RM) *.o distclean: $(RM) Makefile.depends $(TARGETS) *.o clearsilver-0.10.5/cgi/cgi.c0000644001211700116100000011716110645312013012476 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include #include #if defined(HTML_COMPRESSION) #include #endif #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_hdf.h" #include "util/neo_str.h" #include "cgi.h" #include "cgiwrap.h" #include "html.h" #include "cs/cs.h" struct _cgi_vars { char *env_name; char *hdf_name; } CGIVars[] = { {"AUTH_TYPE", "AuthType"}, {"CONTENT_TYPE", "ContentType"}, {"CONTENT_LENGTH", "ContentLength"}, {"DOCUMENT_ROOT", "DocumentRoot"}, {"GATEWAY_INTERFACE", "GatewayInterface"}, {"PATH_INFO", "PathInfo"}, {"PATH_TRANSLATED", "PathTranslated"}, {"QUERY_STRING", "QueryString"}, {"REDIRECT_REQUEST", "RedirectRequest"}, {"REDIRECT_QUERY_STRING", "RedirectQueryString"}, {"REDIRECT_STATUS", "RedirectStatus"}, {"REDIRECT_URL", "RedirectURL",}, {"REMOTE_ADDR", "RemoteAddress"}, {"REMOTE_HOST", "RemoteHost"}, {"REMOTE_IDENT", "RemoteIdent"}, {"REMOTE_PORT", "RemotePort"}, {"REMOTE_USER", "RemoteUser"}, {"REMOTE_GROUP", "RemoteGroup"}, {"REQUEST_METHOD", "RequestMethod"}, {"REQUEST_URI", "RequestURI"}, {"SCRIPT_FILENAME", "ScriptFilename"}, {"SCRIPT_NAME", "ScriptName"}, {"SERVER_ADDR", "ServerAddress"}, {"SERVER_ADMIN", "ServerAdmin"}, {"SERVER_NAME", "ServerName"}, {"SERVER_PORT", "ServerPort"}, {"SERVER_ROOT", "ServerRoot"}, {"SERVER_PROTOCOL", "ServerProtocol"}, {"SERVER_SOFTWARE", "ServerSoftware"}, /* SSL Vars from mod_ssl */ {"HTTPS", "HTTPS"}, {"SSL_PROTOCOL", "SSL.Protocol"}, {"SSL_SESSION_ID", "SSL.SessionID"}, {"SSL_CIPHER", "SSL.Cipher"}, {"SSL_CIPHER_EXPORT", "SSL.Cipher.Export"}, {"SSL_CIPHER_USEKEYSIZE", "SSL.Cipher.UseKeySize"}, {"SSL_CIPHER_ALGKEYSIZE", "SSL.Cipher.AlgKeySize"}, {"SSL_VERSION_INTERFACE", "SSL.Version.Interface"}, {"SSL_VERSION_LIBRARY", "SSL.Version.Library"}, {"SSL_CLIENT_M_VERSION", "SSL.Client.M.Version"}, {"SSL_CLIENT_M_SERIAL", "SSL.Client.M.Serial"}, {"SSL_CLIENT_S_DN", "SSL.Client.S.DN"}, {"SSL_CLIENT_S_DN_x509", "SSL.Client.S.DN.x509"}, {"SSL_CLIENT_I_DN", "SSL.Client.I.DN"}, {"SSL_CLIENT_I_DN_x509", "SSL.Client.I.DN.x509"}, {"SSL_CLIENT_V_START", "SSL.Client.V.Start"}, {"SSL_CLIENT_V_END", "SSL.Client.V.End"}, {"SSL_CLIENT_A_SIG", "SSL.Client.A.SIG"}, {"SSL_CLIENT_A_KEY", "SSL.Client.A.KEY"}, {"SSL_CLIENT_CERT", "SSL.Client.CERT"}, {"SSL_CLIENT_CERT_CHAINn", "SSL.Client.CERT.CHAINn"}, {"SSL_CLIENT_VERIFY", "SSL.Client.Verify"}, {"SSL_SERVER_M_VERSION", "SSL.Server.M.Version"}, {"SSL_SERVER_M_SERIAL", "SSL.Server.M.Serial"}, {"SSL_SERVER_S_DN", "SSL.Server.S.DN"}, {"SSL_SERVER_S_DN_x509", "SSL.Server.S.DN.x509"}, {"SSL_SERVER_S_DN_CN", "SSL.Server.S.DN.CN"}, {"SSL_SERVER_S_DN_EMAIL", "SSL.Server.S.DN.Email"}, {"SSL_SERVER_S_DN_O", "SSL.Server.S.DN.O"}, {"SSL_SERVER_S_DN_OU", "SSL.Server.S.DN.OU"}, {"SSL_SERVER_S_DN_C", "SSL.Server.S.DN.C"}, {"SSL_SERVER_S_DN_SP", "SSL.Server.S.DN.SP"}, {"SSL_SERVER_S_DN_L", "SSL.Server.S.DN.L"}, {"SSL_SERVER_I_DN", "SSL.Server.I.DN"}, {"SSL_SERVER_I_DN_x509", "SSL.Server.I.DN.x509"}, {"SSL_SERVER_I_DN_CN", "SSL.Server.I.DN.CN"}, {"SSL_SERVER_I_DN_EMAIL", "SSL.Server.I.DN.Email"}, {"SSL_SERVER_I_DN_O", "SSL.Server.I.DN.O"}, {"SSL_SERVER_I_DN_OU", "SSL.Server.I.DN.OU"}, {"SSL_SERVER_I_DN_C", "SSL.Server.I.DN.C"}, {"SSL_SERVER_I_DN_SP", "SSL.Server.I.DN.SP"}, {"SSL_SERVER_I_DN_L", "SSL.Server.I.DN.L"}, {"SSL_SERVER_V_START", "SSL.Server.V.Start"}, {"SSL_SERVER_V_END", "SSL.Server.V.End"}, {"SSL_SERVER_A_SIG", "SSL.Server.A.SIG"}, {"SSL_SERVER_A_KEY", "SSL.Server.A.KEY"}, {"SSL_SERVER_CERT", "SSL.Server.CERT"}, /* SSL Vars mapped from others */ /* Hmm, if we're running under mod_ssl w/ +CompatEnvVars, we set these * twice... */ {"SSL_PROTOCOL_VERSION", "SSL.Protocol"}, {"SSLEAY_VERSION", "SSL.Version.Library"}, {"HTTPS_CIPHER", "SSL.Cipher"}, {"HTTPS_EXPORT", "SSL.Cipher.Export"}, {"HTTPS_SECRETKEYSIZE", "SSL.Cipher.UseKeySize"}, {"HTTPS_KEYSIZE", "SSL.Cipher.AlgKeySize"}, {"SSL_SERVER_KEY_SIZE", "SSL.Cipher.AlgKeySize"}, {"SSL_SERVER_CERTIFICATE", "SSL.Server.CERT"}, {"SSL_SERVER_CERT_START", "SSL.Server.V.Start"}, {"SSL_SERVER_CERT_END", "SSL.Server.V.End"}, {"SSL_SERVER_CERT_SERIAL", "SSL.Server.M.Serial"}, {"SSL_SERVER_SIGNATURE_ALGORITHM", "SSL.Server.A.SIG"}, {"SSL_SERVER_DN", "SSL.Server.S.DN"}, {"SSL_SERVER_CN", "SSL.Server.S.DN.CN"}, {"SSL_SERVER_EMAIL", "SSL.Server.S.DN.Email"}, {"SSL_SERVER_O", "SSL.Server.S.DN.O"}, {"SSL_SERVER_OU", "SSL.Server.S.DN.OU"}, {"SSL_SERVER_C", "SSL.Server.S.DN.C"}, {"SSL_SERVER_SP", "SSL.Server.S.DN.SP"}, {"SSL_SERVER_L", "SSL.Server.S.DN.L"}, {"SSL_SERVER_IDN", "SSL.Server.I.DN"}, {"SSL_SERVER_ICN", "SSL.Server.I.DN.CN"}, {"SSL_SERVER_IEMAIL", "SSL.Server.I.DN.Email"}, {"SSL_SERVER_IO", "SSL.Server.I.DN.O"}, {"SSL_SERVER_IOU", "SSL.Server.I.DN.OU"}, {"SSL_SERVER_IC", "SSL.Server.I.DN.C"}, {"SSL_SERVER_ISP", "SSL.Server.I.DN.SP"}, {"SSL_SERVER_IL", "SSL.Server.I.DN.L"}, {"SSL_CLIENT_CERTIFICATE", "SSL.Client.CERT"}, {"SSL_CLIENT_CERT_START", "SSL.Client.V.Start"}, {"SSL_CLIENT_CERT_END", "SSL.Client.V.End"}, {"SSL_CLIENT_CERT_SERIAL", "SSL.Client.M.Serial"}, {"SSL_CLIENT_SIGNATURE_ALGORITHM", "SSL.Client.A.SIG"}, {"SSL_CLIENT_DN", "SSL.Client.S.DN"}, {"SSL_CLIENT_CN", "SSL.Client.S.DN.CN"}, {"SSL_CLIENT_EMAIL", "SSL.Client.S.DN.Email"}, {"SSL_CLIENT_O", "SSL.Client.S.DN.O"}, {"SSL_CLIENT_OU", "SSL.Client.S.DN.OU"}, {"SSL_CLIENT_C", "SSL.Client.S.DN.C"}, {"SSL_CLIENT_SP", "SSL.Client.S.DN.SP"}, {"SSL_CLIENT_L", "SSL.Client.S.DN.L"}, {"SSL_CLIENT_IDN", "SSL.Client.I.DN"}, {"SSL_CLIENT_ICN", "SSL.Client.I.DN.CN"}, {"SSL_CLIENT_IEMAIL", "SSL.Client.I.DN.Email"}, {"SSL_CLIENT_IO", "SSL.Client.I.DN.O"}, {"SSL_CLIENT_IOU", "SSL.Client.I.DN.OU"}, {"SSL_CLIENT_IC", "SSL.Client.I.DN.C"}, {"SSL_CLIENT_ISP", "SSL.Client.I.DN.SP"}, {"SSL_CLIENT_IL", "SSL.Client.I.DN.L"}, {"SSL_EXPORT", "SSL.Cipher.Export"}, {"SSL_KEYSIZE", "SSL.Cipher.AlgKeySize"}, {"SSL_SECKEYSIZE", "SSL.Cipher.UseKeySize"}, {"SSL_SSLEAY_VERSION", "SSL.Version.Library"}, /* Old vars not in mod_ssl */ {"SSL_STRONG_CRYPTO", "SSL.Strong.Crypto"}, {"SSL_SERVER_KEY_EXP", "SSL.Server.Key.Exp"}, {"SSL_SERVER_KEY_ALGORITHM", "SSL.Server.Key.Algorithm"}, {"SSL_SERVER_KEY_SIZE", "SSL.Server.Key.Size"}, {"SSL_SERVER_SESSIONDIR", "SSL.Server.SessionDir"}, {"SSL_SERVER_CERTIFICATELOGDIR", "SSL.Server.CertificateLogDir"}, {"SSL_SERVER_CERTFILE", "SSL.Server.CertFile"}, {"SSL_SERVER_KEYFILE", "SSL.Server.KeyFile"}, {"SSL_SERVER_KEYFILETYPE", "SSL.Server.KeyFileType"}, {"SSL_CLIENT_KEY_EXP", "SSL.Client.Key.Exp"}, {"SSL_CLIENT_KEY_ALGORITHM", "SSL.Client.Key.Algorithm"}, {"SSL_CLIENT_KEY_SIZE", "SSL.Client.Key.Size"}, {NULL, NULL} }; struct _http_vars { char *env_name; char *hdf_name; } HTTPVars[] = { {"HTTP_ACCEPT", "Accept"}, {"HTTP_ACCEPT_CHARSET", "AcceptCharset"}, {"HTTP_ACCEPT_ENCODING", "AcceptEncoding"}, {"HTTP_ACCEPT_LANGUAGE", "AcceptLanguage"}, {"HTTP_COOKIE", "Cookie"}, {"HTTP_HOST", "Host"}, {"HTTP_USER_AGENT", "UserAgent"}, {"HTTP_IF_MODIFIED_SINCE", "IfModifiedSince"}, {"HTTP_REFERER", "Referer"}, {"HTTP_VIA", "Via"}, /* SOAP */ {"HTTP_SOAPACTION", "Soap.Action"}, {NULL, NULL} }; static char *Argv0 = ""; int IgnoreEmptyFormVars = 0; static int ExceptionsInit = 0; NERR_TYPE CGIFinished = -1; NERR_TYPE CGIUploadCancelled = -1; NERR_TYPE CGIParseNotHandled = -1; static NEOERR *_add_cgi_env_var (CGI *cgi, char *env, char *name) { NEOERR *err; char *s; err = cgiwrap_getenv (env, &s); if (err != STATUS_OK) return nerr_pass (err); if (s != NULL) { err = hdf_set_buf (cgi->hdf, name, s); if (err != STATUS_OK) { free(s); return nerr_pass (err); } } return STATUS_OK; } char *cgi_url_unescape (char *value) { int i = 0, o = 0; unsigned char *s = (unsigned char *)value; if (s == NULL) return value; while (s[i]) { if (s[i] == '+') { s[o++] = ' '; i++; } else if (s[i] == '%' && isxdigit(s[i+1]) && isxdigit(s[i+2])) { char num; num = (s[i+1] >= 'A') ? ((s[i+1] & 0xdf) - 'A') + 10 : (s[i+1] - '0'); num *= 16; num += (s[i+2] >= 'A') ? ((s[i+2] & 0xdf) - 'A') + 10 : (s[i+2] - '0'); s[o++] = num; i+=3; } else { s[o++] = s[i++]; } } if (i && o) s[o] = '\0'; return (char *)s; } NEOERR *cgi_js_escape (const char *in, char **esc) { return nerr_pass(neos_js_escape(in, esc)); } NEOERR *cgi_url_escape (const char *buf, char **esc) { return nerr_pass(neos_url_escape(buf, esc, NULL)); } NEOERR *cgi_url_escape_more (const char *in, char **esc, const char *other) { return nerr_pass(neos_url_escape(in, esc, other)); } NEOERR *cgi_url_validate (const char *buf, char **esc) { return nerr_pass(neos_url_validate(buf, esc)); } static NEOERR *_parse_query (CGI *cgi, char *query) { NEOERR *err = STATUS_OK; char *t, *k, *v, *l; char buf[256]; char unnamed[10]; int unnamed_count = 0; HDF *obj, *child; if (query && *query) { k = strtok_r(query, "&", &l); while (k && *k) { v = strchr(k, '='); if (v == NULL) { v = ""; } else { *v = '\0'; v++; } /* Check for some invalid query strings */ if (*k == 0) { /* '?=foo' gets mapped in as Query._1=foo */ snprintf(unnamed,sizeof(unnamed), "_%d", unnamed_count++); k = unnamed; } else if (*k == '.') { /* an hdf element can't start with a period */ *k = '_'; } snprintf(buf, sizeof(buf), "Query.%s", cgi_url_unescape(k)); if (!(cgi->ignore_empty_form_vars && (*v == '\0'))) { cgi_url_unescape(v); obj = hdf_get_obj (cgi->hdf, buf); if (obj != NULL) { int i = 0; char buf2[10]; child = hdf_obj_child (obj); if (child == NULL) { t = hdf_obj_value (obj); err = hdf_set_value (obj, "0", t); if (err != STATUS_OK) break; i = 1; } else { while (child != NULL) { i++; child = hdf_obj_next (child); if (err != STATUS_OK) break; } if (err != STATUS_OK) break; } snprintf (buf2, sizeof(buf2), "%d", i); err = hdf_set_value (obj, buf2, v); if (err != STATUS_OK) break; } err = hdf_set_value (cgi->hdf, buf, v); if (nerr_match(err, NERR_ASSERT)) { STRING str; string_init(&str); nerr_error_string(err, &str); ne_warn("Unable to set Query value: %s = %s: %s", buf, v, str.buf); string_clear(&str); nerr_ignore(&err); } if (err != STATUS_OK) break; } k = strtok_r(NULL, "&", &l); } } return nerr_pass(err); } /* Is it an error if its a short read? */ static NEOERR *_parse_post_form (CGI *cgi) { NEOERR *err = STATUS_OK; char *l, *query; int len, r, o; l = hdf_get_value (cgi->hdf, "CGI.ContentLength", NULL); if (l == NULL) return STATUS_OK; len = atoi (l); if (len <= 0) return STATUS_OK; cgi->data_expected = len; query = (char *) malloc (sizeof(char) * (len + 1)); if (query == NULL) return nerr_raise (NERR_NOMEM, "Unable to allocate memory to read POST input of length %d", len); o = 0; while (o < len) { cgiwrap_read (query + o, len - o, &r); if (r <= 0) break; o = o + r; } if (r < 0) { free(query); return nerr_raise_errno (NERR_IO, "Short read on CGI POST input (%d < %d)", o, len); } if (o != len) { free(query); return nerr_raise (NERR_IO, "Short read on CGI POST input (%d < %d)", o, len); } query[len] = '\0'; err = _parse_query (cgi, query); free(query); return nerr_pass(err); } static NEOERR *_parse_cookie (CGI *cgi) { NEOERR *err; char *cookie; char *k, *v, *l; HDF *obj; err = hdf_get_copy (cgi->hdf, "HTTP.Cookie", &cookie, NULL); if (err != STATUS_OK) return nerr_pass(err); if (cookie == NULL) return STATUS_OK; err = hdf_set_value (cgi->hdf, "Cookie", cookie); if (err != STATUS_OK) { free(cookie); return nerr_pass(err); } obj = hdf_get_obj (cgi->hdf, "Cookie"); k = l = cookie; while (*l && *l != '=' && *l != ';') l++; while (*k) { if (*l == '=') { if (*l) *l++ = '\0'; v = l; while (*l && *l != ';') l++; if (*l) *l++ = '\0'; } else { v = ""; if (*l) *l++ = '\0'; } k = neos_strip (k); v = neos_strip (v); if (k[0] && v[0]) { err = hdf_set_value (obj, k, v); if (nerr_match(err, NERR_ASSERT)) { STRING str; string_init(&str); nerr_error_string(err, &str); ne_warn("Unable to set Cookie value: %s = %s: %s", k, v, str.buf); string_clear(&str); nerr_ignore(&err); } if (err) break; } k = l; while (*l && *l != '=' && *l != ';') l++; } free (cookie); return nerr_pass(err); } #ifdef ENABLE_REMOTE_DEBUG static void _launch_debugger (CGI *cgi, char *display) { pid_t myPid, pid; char buffer[127]; char *debugger; HDF *obj; char *allowed; /* Only allow remote debugging from allowed hosts */ for (obj = hdf_get_child (cgi->hdf, "Config.Displays"); obj; obj = hdf_obj_next (obj)) { allowed = hdf_obj_value (obj); if (allowed && !strcmp (display, allowed)) break; } if (obj == NULL) return; myPid = getpid(); if ((pid = fork()) < 0) return; if ((debugger = hdf_get_value (cgi->hdf, "Config.Debugger", NULL)) == NULL) { debugger = "/usr/local/bin/sudo /usr/local/bin/ddd -display %s %s %d"; } if (!pid) { sprintf(buffer, debugger, display, Argv0, myPid); execl("/bin/sh", "sh", "-c", buffer, NULL); } else { sleep(60); } } #endif static NEOERR *cgi_pre_parse (CGI *cgi) { NEOERR *err; int x = 0; char buf[256]; char *query; while (CGIVars[x].env_name) { snprintf (buf, sizeof(buf), "CGI.%s", CGIVars[x].hdf_name); err = _add_cgi_env_var(cgi, CGIVars[x].env_name, buf); if (err != STATUS_OK) return nerr_pass (err); x++; } x = 0; while (HTTPVars[x].env_name) { snprintf (buf, sizeof(buf), "HTTP.%s", HTTPVars[x].hdf_name); err = _add_cgi_env_var(cgi, HTTPVars[x].env_name, buf); if (err != STATUS_OK) return nerr_pass (err); x++; } err = _parse_cookie(cgi); if (err != STATUS_OK) return nerr_pass (err); err = hdf_get_copy (cgi->hdf, "CGI.QueryString", &query, NULL); if (err != STATUS_OK) return nerr_pass (err); if (query != NULL) { err = _parse_query(cgi, query); free(query); if (err != STATUS_OK) return nerr_pass (err); } { char *d = hdf_get_value(cgi->hdf, "Query.debug_pause", NULL); char *d_p = hdf_get_value(cgi->hdf, "Config.DebugPassword", NULL); if (hdf_get_int_value(cgi->hdf, "Config.DebugEnabled", 0) && d && d_p && !strcmp(d, d_p)) { sleep(20); } } #ifdef ENABLE_REMOTE_DEBUG { char *display; display = hdf_get_value (cgi->hdf, "Query.xdisplay", NULL); if (display) { fprintf(stderr, "** Got display %s\n", display); _launch_debugger(cgi, display); } } #endif return STATUS_OK; } NEOERR *cgi_register_parse_cb(CGI *cgi, const char *method, const char *ctype, void *rock, CGI_PARSE_CB parse_cb) { struct _cgi_parse_cb *my_pcb; if (method == NULL || ctype == NULL) return nerr_raise(NERR_ASSERT, "method and type must not be NULL to register cb"); my_pcb = (struct _cgi_parse_cb *) calloc(1, sizeof(struct _cgi_parse_cb)); if (my_pcb == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory to register parse cb"); my_pcb->method = strdup(method); my_pcb->ctype = strdup(ctype); if (my_pcb->method == NULL || my_pcb->ctype == NULL) { if (my_pcb->method != NULL) free(my_pcb->method); if (my_pcb->ctype != NULL) free(my_pcb->ctype); free(my_pcb); return nerr_raise(NERR_NOMEM, "Unable to allocate memory to register parse cb"); } if (!strcmp(my_pcb->method, "*")) my_pcb->any_method = 1; if (!strcmp(my_pcb->ctype, "*")) my_pcb->any_ctype = 1; my_pcb->rock = rock; my_pcb->parse_cb = parse_cb; my_pcb->next = cgi->parse_callbacks; cgi->parse_callbacks = my_pcb; return STATUS_OK; } NEOERR *cgi_parse (CGI *cgi) { NEOERR *err; char *method, *type; struct _cgi_parse_cb *pcb; method = hdf_get_value (cgi->hdf, "CGI.RequestMethod", "GET"); type = hdf_get_value (cgi->hdf, "CGI.ContentType", NULL); /* Walk the registered parse callbacks for a matching one */ pcb = cgi->parse_callbacks; while (pcb != NULL) { if ( (pcb->any_method || !strcasecmp(pcb->method, method)) && (pcb->any_ctype || (type && !strcasecmp(pcb->ctype, type))) ) { err = pcb->parse_cb(cgi, method, type, pcb->rock); if (err && !nerr_handle(&err, CGIParseNotHandled)) return nerr_pass(err); } pcb = pcb->next; } /* Fallback to internal methods */ if (!strcmp(method, "POST")) { if (type && !strcmp(type, "application/x-www-form-urlencoded")) { err = _parse_post_form(cgi); if (err != STATUS_OK) return nerr_pass (err); } else if (type && !strncmp (type, "multipart/form-data", 19)) { err = parse_rfc2388 (cgi); if (err != STATUS_OK) return nerr_pass (err); } #if 0 else { int len, x, r; char *l; char buf[4096]; FILE *fp; fp = fopen("/tmp/upload", "w"); l = hdf_get_value (cgi->hdf, "CGI.ContentLength", NULL); if (l == NULL) return STATUS_OK; len = atoi (l); x = 0; while (x < len) { if (len-x > sizeof(buf)) cgiwrap_read (buf, sizeof(buf), &r); else cgiwrap_read (buf, len - x, &r); fwrite (buf, 1, r, fp); x += r; } fclose (fp); if (err) return nerr_pass(err); } #endif } else if (!strcmp(method, "PUT")) { FILE *fp; int len, x, r, w; char *l; char buf[4096]; int unlink_files = hdf_get_int_value(cgi->hdf, "Config.Upload.Unlink", 1); err = open_upload(cgi, unlink_files, &fp); if (err) return nerr_pass(err); l = hdf_get_value (cgi->hdf, "CGI.ContentLength", NULL); if (l == NULL) return STATUS_OK; len = atoi (l); if (len <= 0) return STATUS_OK; x = 0; while (x < len) { if (len-x > sizeof(buf)) cgiwrap_read (buf, sizeof(buf), &r); else cgiwrap_read (buf, len - x, &r); w = fwrite (buf, sizeof(char), r, fp); if (w != r) { err = nerr_raise_errno(NERR_IO, "Short write on PUT: %d < %d", w, r); break; } x += r; } if (err) return nerr_pass(err); fseek(fp, 0, SEEK_SET); l = hdf_get_value(cgi->hdf, "CGI.PathInfo", NULL); if (l) err = hdf_set_value (cgi->hdf, "PUT", l); if (err) return nerr_pass(err); if (type) err = hdf_set_value (cgi->hdf, "PUT.Type", type); if (err) return nerr_pass(err); err = hdf_set_int_value (cgi->hdf, "PUT.FileHandle", uListLength(cgi->files)); if (err) return nerr_pass(err); if (!unlink_files) { char *name; err = uListGet(cgi->filenames, uListLength(cgi->filenames)-1, (void *)&name); if (err) return nerr_pass(err); err = hdf_set_value (cgi->hdf, "PUT.FileName", name); if (err) return nerr_pass(err); } } return STATUS_OK; } NEOERR *cgi_init (CGI **cgi, HDF *hdf) { NEOERR *err = STATUS_OK; CGI *mycgi; if (ExceptionsInit == 0) { err = nerr_init(); if (err) return nerr_pass(err); err = nerr_register(&CGIFinished, "CGIFinished"); if (err) return nerr_pass(err); err = nerr_register(&CGIUploadCancelled, "CGIUploadCancelled"); if (err) return nerr_pass(err); err = nerr_register(&CGIUploadCancelled, "CGIParseNotHandled"); if (err) return nerr_pass(err); ExceptionsInit = 1; } *cgi = NULL; mycgi = (CGI *) calloc (1, sizeof(CGI)); if (mycgi == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate space for CGI"); mycgi->time_start = ne_timef(); mycgi->ignore_empty_form_vars = IgnoreEmptyFormVars; do { if (hdf == NULL) { err = hdf_init (&(mycgi->hdf)); if (err != STATUS_OK) break; } else { mycgi->hdf = hdf; } err = cgi_pre_parse (mycgi); if (err != STATUS_OK) break; } while (0); if (err == STATUS_OK) *cgi = mycgi; else { cgi_destroy(&mycgi); } return nerr_pass(err); } static void _destroy_tmp_file(char *filename) { unlink(filename); free(filename); } void cgi_destroy (CGI **cgi) { CGI *my_cgi; if (!cgi || !*cgi) return; my_cgi = *cgi; if (my_cgi->hdf) hdf_destroy (&(my_cgi->hdf)); if (my_cgi->buf) free(my_cgi->buf); if (my_cgi->files) uListDestroyFunc(&(my_cgi->files), (void (*)(void *))fclose); if (my_cgi->filenames) uListDestroyFunc(&(my_cgi->filenames), (void (*)(void *))_destroy_tmp_file); free (*cgi); *cgi = NULL; } static NEOERR *render_cb (void *ctx, char *buf) { STRING *str = (STRING *)ctx; NEOERR *err; err = nerr_pass(string_append(str, buf)); return err; } static NEOERR *cgi_headers (CGI *cgi) { NEOERR *err = STATUS_OK; HDF *obj, *child; char *s, *charset = NULL; if (hdf_get_int_value (cgi->hdf, "Config.NoCache", 0)) { /* Ok, we try really hard to defeat caches here */ /* this isn't in any HTTP rfc's, it just seems to be a convention */ err = cgiwrap_writef ("Pragma: no-cache\r\n"); if (err != STATUS_OK) return nerr_pass (err); err = cgiwrap_writef ("Expires: Fri, 01 Jan 1990 00:00:00 GMT\r\n"); if (err != STATUS_OK) return nerr_pass (err); err = cgiwrap_writef ("Cache-control: no-cache, must-revalidate, no-cache=\"Set-Cookie\", private\r\n"); if (err != STATUS_OK) return nerr_pass (err); } obj = hdf_get_obj (cgi->hdf, "cgiout"); if (obj) { s = hdf_get_value (obj, "Status", NULL); if (s) err = cgiwrap_writef ("Status: %s\r\n", s); if (err != STATUS_OK) return nerr_pass (err); s = hdf_get_value (obj, "Location", NULL); if (s) err = cgiwrap_writef ("Location: %s\r\n", s); if (err != STATUS_OK) return nerr_pass (err); child = hdf_get_obj (cgi->hdf, "cgiout.other"); if (child) { child = hdf_obj_child (child); while (child != NULL) { s = hdf_obj_value (child); err = cgiwrap_writef ("%s\r\n", s); if (err != STATUS_OK) return nerr_pass (err); child = hdf_obj_next(child); } } charset = hdf_get_value (obj, "charset", NULL); s = hdf_get_value (obj, "ContentType", "text/html"); if (charset) err = cgiwrap_writef ("Content-Type: %s; charset=%s\r\n\r\n", s, charset); else err = cgiwrap_writef ("Content-Type: %s\r\n\r\n", s); if (err != STATUS_OK) return nerr_pass (err); } else { /* Default */ err = cgiwrap_writef ("Content-Type: text/html\r\n\r\n"); if (err != STATUS_OK) return nerr_pass (err); } return STATUS_OK; } #if defined(HTML_COMPRESSION) /* Copy these here from zutil.h, which we aren't supposed to include */ #define DEF_MEM_LEVEL 8 #define OS_CODE 0x03 static NEOERR *cgi_compress (STRING *str, char *obuf, int *olen) { z_stream stream; int err; stream.next_in = (Bytef*)str->buf; stream.avail_in = (uInt)str->len; stream.next_out = (Bytef*)obuf; stream.avail_out = (uInt)*olen; if ((uLong)stream.avail_out != *olen) return nerr_raise(NERR_NOMEM, "Destination too big: %d", *olen); stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; /* err = deflateInit(&stream, Z_DEFAULT_COMPRESSION); */ err = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); if (err != Z_OK) return nerr_raise(NERR_SYSTEM, "deflateInit2 returned %d", err); err = deflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { deflateEnd(&stream); return nerr_raise(NERR_SYSTEM, "deflate returned %d", err); } *olen = stream.total_out; err = deflateEnd(&stream); return STATUS_OK; } #endif /* This ws strip function is Dave's version, designed to make debug * easier, and the output a bit smaller... but not as small as it could * be: essentially, it strips all empty lines, all extra space at the * end of the line, except in pre/textarea tags. * * Ok, expanding to 3 levels: * 0 - No stripping * 1 - Dave's debug stripper (as above) * 2 - strip all extra white space * * We don't currently strip white space in a tag * * */ #if 0 static void debug_output(char *header, char *s, int n) { int x; fprintf (stderr, "%s ", header); for (x = 0; x < n; x++) { fprintf (stderr, "%c", s[x]); } fprintf(stderr, "\n"); } #endif void cgi_html_ws_strip(STRING *str, int level) { int ws = 0; int seen_nonws = level > 1; int i, o, l; char *ch; i = o = 0; if (str->len) { ws = isspace(str->buf[0]); } while (i < str->len) { if (str->buf[i] == '<') { str->buf[o++] = str->buf[i++]; if (!strncasecmp(str->buf + i, "textarea", 8)) { ch = str->buf + i; do { ch = strchr(ch, '<'); if (ch == NULL) { memmove(str->buf + o, str->buf + i, str->len - i); str->len = o + str->len - i; str->buf[str->len] = '\0'; return; } ch++; } while (strncasecmp(ch, "/textarea>", 10)); ch += 10; l = ch - str->buf - i; memmove(str->buf + o, str->buf + i, l); o += l; i += l; } else if (!strncasecmp(str->buf + i, "pre", 3)) { ch = str->buf + i; do { ch = strchr(ch, '<'); if (ch == NULL) { memmove(str->buf + o, str->buf + i, str->len - i); str->len = o + str->len - i; str->buf[str->len] = '\0'; return; } ch++; } while (strncasecmp(ch, "/pre>", 5)); ch += 5; l = ch - str->buf - i; memmove(str->buf + o, str->buf + i, l); o += l; i += l; } else { ch = strchr(str->buf + i, '>'); if (ch == NULL) { memmove(str->buf + o, str->buf + i, str->len - i); str->len = o + str->len - i; str->buf[str->len] = '\0'; return; } ch++; /* debug_output("copying tag", str->buf + i, ch - str->buf - i); * */ l = ch - str->buf - i; memmove(str->buf + o, str->buf + i, l); o += l; i += l; } /* debug_output("result", str->buf, o); */ seen_nonws = 1; ws = 0; } else if (str->buf[i] == '\n') { /* This has the effect of erasing all whitespace at the eol plus * erasing all blank lines */ while (o && isspace(str->buf[o-1])) o--; str->buf[o++] = str->buf[i++]; ws = level > 1; seen_nonws = level > 1; } else if (seen_nonws && isspace(str->buf[i])) { if (ws) { i++; } else { str->buf[o++] = str->buf[i++]; ws = 1; } } else { seen_nonws = 1; ws = 0; str->buf[o++] = str->buf[i++]; } } str->len = o; str->buf[str->len] = '\0'; } NEOERR *cgi_output (CGI *cgi, STRING *str) { NEOERR *err = STATUS_OK; double dis; int is_html = 0; int use_deflate = 0; int use_gzip = 0; int do_debug = 0; int do_timefooter = 0; int ws_strip_level = 0; char *s, *e; s = hdf_get_value (cgi->hdf, "Query.debug", NULL); e = hdf_get_value (cgi->hdf, "Config.DebugPassword", NULL); if (hdf_get_int_value(cgi->hdf, "Config.DebugEnabled", 0) && s && e && !strcmp(s, e)) do_debug = 1; do_timefooter = hdf_get_int_value (cgi->hdf, "Config.TimeFooter", 1); ws_strip_level = hdf_get_int_value (cgi->hdf, "Config.WhiteSpaceStrip", 1); dis = ne_timef(); s = hdf_get_value (cgi->hdf, "cgiout.ContentType", "text/html"); if (!strcasecmp(s, "text/html")) is_html = 1; #if defined(HTML_COMPRESSION) /* Determine whether or not we can compress the output */ if (is_html && hdf_get_int_value (cgi->hdf, "Config.CompressionEnabled", 0)) { err = hdf_get_copy (cgi->hdf, "HTTP.AcceptEncoding", &s, NULL); if (err != STATUS_OK) return nerr_pass (err); if (s) { char *next; e = strtok_r (s, ",", &next); while (e && !use_deflate) { if (strstr(e, "deflate") != NULL) { use_deflate = 1; use_gzip = 0; } else if (strstr(e, "gzip") != NULL) use_gzip = 1; e = strtok_r (NULL, ",", &next); } free (s); } s = hdf_get_value (cgi->hdf, "HTTP.UserAgent", NULL); if (s) { if (strstr(s, "MSIE 4") || strstr(s, "MSIE 5") || strstr(s, "MSIE 6")) { e = hdf_get_value (cgi->hdf, "HTTP.Accept", NULL); if (e && !strcmp(e, "*/*")) { use_deflate = 0; use_gzip = 0; } } else { if (strncasecmp(s, "mozilla/5.", 10)) { use_deflate = 0; use_gzip = 0; } } } else { use_deflate = 0; use_gzip = 0; } if (use_deflate) { err = hdf_set_value (cgi->hdf, "cgiout.other.encoding", "Content-Encoding: deflate"); } else if (use_gzip) { err = hdf_set_value (cgi->hdf, "cgiout.other.encoding", "Content-Encoding: gzip"); } if (err != STATUS_OK) return nerr_pass(err); } #endif err = cgi_headers(cgi); if (err != STATUS_OK) return nerr_pass(err); if (is_html) { char buf[50]; int x; if (do_timefooter) { snprintf (buf, sizeof(buf), "\n\n", dis - cgi->time_start, use_deflate || use_gzip); err = string_append (str, buf); if (err != STATUS_OK) return nerr_pass(err); } if (ws_strip_level) { cgi_html_ws_strip(str, ws_strip_level); } if (do_debug) { err = string_append (str, "
"); if (err != STATUS_OK) return nerr_pass(err); x = 0; while (1) { char *k, *v; err = cgiwrap_iterenv (x, &k, &v); if (err != STATUS_OK) return nerr_pass(err); if (k == NULL) break; err =string_appendf (str, "%s = %s
", k, v); if (err != STATUS_OK) return nerr_pass(err); free(k); free(v); x++; } err = string_append (str, "
");
      if (err != STATUS_OK) return nerr_pass(err);
      err = hdf_dump_str (cgi->hdf, NULL, 0, str);
      if (err != STATUS_OK) return nerr_pass(err);
    }
  }

#if defined(HTML_COMPRESSION)
    if (is_html && (use_deflate || use_gzip))
    {
      char *dest;
      static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
      char gz_buf[20]; /* gzip header/footer buffer, len of header is 10 bytes */
      unsigned int crc = 0;
      int len2;

      if (use_gzip)
      {
	crc = crc32(0L, Z_NULL, 0);
	crc = crc32(crc, (const Bytef *)(str->buf), str->len);
      }
      len2 = str->len * 2;
      dest = (char *) malloc (sizeof(char) * len2);
      if (dest != NULL)
      {
	do {
	  err = cgi_compress (str, dest, &len2);
	  if (err == STATUS_OK)
	  {
	    if (use_gzip)
	    {
	      /* I'm using sprintf instead of cgiwrap_writef since
	       * the wrapper writef might not handle values with
	       * embedded NULLs... though I should fix the python one
	       * now as well */
	      sprintf(gz_buf, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
		  Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/,
		  OS_CODE);
	      err = cgiwrap_write(gz_buf, 10);
	    }
	    if (err != STATUS_OK) break;
	    err = cgiwrap_write(dest, len2);
	    if (err != STATUS_OK) break;

	    if (use_gzip)
	    {
	      /* write crc and len in network order */
	      sprintf(gz_buf, "%c%c%c%c%c%c%c%c",
		  (0xff & (crc >> 0)),
		  (0xff & (crc >> 8)),
		  (0xff & (crc >> 16)),
		  (0xff & (crc >> 24)),
		  (0xff & (str->len >> 0)),
		  (0xff & (str->len >> 8)),
		  (0xff & (str->len >> 16)),
		  (0xff & (str->len >> 24)));
	      err = cgiwrap_write(gz_buf, 8);
	      if (err != STATUS_OK) break;
	    }
	  }
	  else
	  {
	    nerr_log_error (err);
	    err = cgiwrap_write(str->buf, str->len);
	  }
	} while (0);
	free (dest);
      }
      else
      {
	err = cgiwrap_write(str->buf, str->len);
      }
    }
    else
#endif
    {
      err = cgiwrap_write(str->buf, str->len);
    }

  return nerr_pass(err);
}

NEOERR *cgi_html_escape_strfunc(const char *str, char **ret)
{
  return nerr_pass(html_escape_alloc(str, strlen(str), ret));
}

NEOERR *cgi_html_strip_strfunc(const char *str, char **ret)
{
  return nerr_pass(html_strip_alloc(str, strlen(str), ret));
}

NEOERR *cgi_text_html_strfunc(const char *str, char **ret)
{
  return nerr_pass(convert_text_html_alloc(str, strlen(str), ret));
}

NEOERR *cgi_register_strfuncs(CSPARSE *cs)
{
  NEOERR *err;

  err = cs_register_esc_strfunc(cs, "url_escape", cgi_url_escape);
  if (err != STATUS_OK) return nerr_pass(err);
  err = cs_register_esc_strfunc(cs, "html_escape", cgi_html_escape_strfunc);
  if (err != STATUS_OK) return nerr_pass(err);
  err = cs_register_strfunc(cs, "text_html", cgi_text_html_strfunc);
  if (err != STATUS_OK) return nerr_pass(err);
  err = cs_register_esc_strfunc(cs, "js_escape", cgi_js_escape);
  if (err != STATUS_OK) return nerr_pass(err);
  err = cs_register_strfunc(cs, "html_strip", cgi_html_strip_strfunc);
  if (err != STATUS_OK) return nerr_pass(err);
  err = cs_register_esc_strfunc(cs, "url_validate", cgi_url_validate);
  if (err != STATUS_OK) return nerr_pass(err);
  return STATUS_OK;
}

NEOERR *cgi_cs_init(CGI *cgi, CSPARSE **cs)
{
  NEOERR *err;

  *cs = NULL;

  do
  {
    err = cs_init (cs, cgi->hdf);
    if (err != STATUS_OK) break;
    err = cgi_register_strfuncs(*cs);
    if (err != STATUS_OK) break;
  } while (0);

  if (err && *cs) cs_destroy(cs);
  return nerr_pass(err);
}

NEOERR *cgi_display (CGI *cgi, const char *cs_file)
{
  NEOERR *err = STATUS_OK;
  char *debug;
  CSPARSE *cs = NULL;
  STRING str;
  int do_dump = 0;
  char *t;

  string_init(&str);

  debug = hdf_get_value (cgi->hdf, "Query.debug", NULL);
  t = hdf_get_value (cgi->hdf, "Config.DumpPassword", NULL);
  if (hdf_get_int_value(cgi->hdf, "Config.DebugEnabled", 0) &&
      debug && t && !strcmp (debug, t)) do_dump = 1;

  do
  {
    err = cs_init (&cs, cgi->hdf);
    if (err != STATUS_OK) break;
    err = cgi_register_strfuncs(cs);
    if (err != STATUS_OK) break;
    err = cs_parse_file (cs, cs_file);
    if (err != STATUS_OK) break;
    if (do_dump)
    {
      cgiwrap_writef("Content-Type: text/plain\n\n");
      hdf_dump_str(cgi->hdf, "", 0, &str);
      cs_dump(cs, &str, render_cb);
      cgiwrap_writef("%s", str.buf);
      break;
    }
    else
    {
      err = cs_render (cs, &str, render_cb);
      if (err != STATUS_OK) break;
    }
    err = cgi_output(cgi, &str);
    if (err != STATUS_OK) break;
  } while (0);

  cs_destroy(&cs);
  string_clear (&str);
  return nerr_pass(err);
}

void cgi_neo_error (CGI *cgi, NEOERR *err)
{
  STRING str;

  string_init(&str);
  cgiwrap_writef("Status: 500\n");
  cgiwrap_writef("Content-Type: text/html\n\n");

  cgiwrap_writef("\nAn error occured:
");
  nerr_error_traceback(err, &str);
  cgiwrap_write(str.buf, str.len);
  cgiwrap_writef("
\n"); } void cgi_error (CGI *cgi, const char *fmt, ...) { va_list ap; cgiwrap_writef("Status: 500\n"); cgiwrap_writef("Content-Type: text/html\n\n"); cgiwrap_writef("\nAn error occured:
");
  va_start (ap, fmt);
  cgiwrap_writevf (fmt, ap);
  va_end (ap);
  cgiwrap_writef("
\n"); } void cgi_debug_init (int argc, char **argv) { FILE *fp; char line[4096]; char *v, *k; Argv0 = argv[0]; if (argc) { fp = fopen(argv[1], "r"); if (fp == NULL) return; while (fgets(line, sizeof(line), fp) != NULL) { v = strchr(line, '='); if (v != NULL) { *v = '\0'; v = neos_strip(v+1); k = neos_strip(line); cgiwrap_putenv (line, v); } } fclose(fp); } } void cgi_vredirect (CGI *cgi, int uri, const char *fmt, va_list ap) { cgiwrap_writef ("Status: 302\r\n"); cgiwrap_writef ("Content-Type: text/html\r\n"); cgiwrap_writef ("Pragma: no-cache\r\n"); cgiwrap_writef ("Expires: Fri, 01 Jan 1999 00:00:00 GMT\r\n"); cgiwrap_writef ("Cache-control: no-cache, no-cache=\"Set-Cookie\", private\r\n"); if (uri) { cgiwrap_writef ("Location: "); } else { char *host; int https = 0; if (!strcmp(hdf_get_value(cgi->hdf, "CGI.HTTPS", "off"), "on")) { https = 1; } host = hdf_get_value (cgi->hdf, "HTTP.Host", NULL); if (host == NULL) host = hdf_get_value (cgi->hdf, "CGI.ServerName", "localhost"); cgiwrap_writef ("Location: %s://%s", https ? "https" : "http", host); if ((strchr(host, ':') == NULL)) { int port = hdf_get_int_value(cgi->hdf, "CGI.ServerPort", 80); if (!((https && port == 443) || (!https && port == 80))) { cgiwrap_writef(":%d", port); } } } cgiwrap_writevf (fmt, ap); cgiwrap_writef ("\r\n\r\n"); cgiwrap_writef ("Redirect page

\n"); #if 0 /* Apparently this crashes on some computers... I don't know if its * legal to reuse the va_list */ cgiwrap_writef (" Destination:
"); cgiwrap_writevf (fmt, ap); cgiwrap_writef ("
\n
\n"); #endif cgiwrap_writef ("There is nothing to see here, please move along..."); } void cgi_redirect (CGI *cgi, const char *fmt, ...) { va_list ap; va_start(ap, fmt); cgi_vredirect (cgi, 0, fmt, ap); va_end(ap); return; } void cgi_redirect_uri (CGI *cgi, const char *fmt, ...) { va_list ap; va_start(ap, fmt); cgi_vredirect (cgi, 1, fmt, ap); va_end(ap); return; } char *cgi_cookie_authority (CGI *cgi, const char *host) { HDF *obj; char *domain; int hlen = 0, dlen = 0; if (host == NULL) { host = hdf_get_value (cgi->hdf, "HTTP.Host", NULL); } if (host == NULL) return NULL; while (host[hlen] && host[hlen] != ':') hlen++; obj = hdf_get_obj (cgi->hdf, "CookieAuthority"); if (obj == NULL) return NULL; for (obj = hdf_obj_child (obj); obj; obj = hdf_obj_next (obj)) { domain = hdf_obj_value (obj); dlen = strlen(domain); if (hlen >= dlen) { if (!strncasecmp (host + hlen - dlen, domain, dlen)) return domain; } } return NULL; } /* For more information about Cookies, see: * The original Netscape Cookie Spec: * http://wp.netscape.com/newsref/std/cookie_spec.html * * HTTP State Management Mechanism * http://www.ietf.org/rfc/rfc2109.txt */ NEOERR *cgi_cookie_set (CGI *cgi, const char *name, const char *value, const char *path, const char *domain, const char *time_str, int persistent, int secure) { NEOERR *err; STRING str; char my_time[256]; if (path == NULL) path = "/"; string_init(&str); do { err = string_appendf(&str, "Set-Cookie: %s=%s; path=%s", name, value, path); if (err) break; if (persistent) { if (time_str == NULL) { /* Expires in one year */ time_t exp_date = time(NULL) + 31536000; strftime (my_time, 48, "%A, %d-%b-%Y 23:59:59 GMT", gmtime (&exp_date)); time_str = my_time; } err = string_appendf(&str, "; expires=%s", time_str); if (err) break; } if (domain) { err = string_appendf(&str, "; domain=%s", domain); if (err) break; } if (secure) { err = string_append(&str, "; secure"); if (err) break; } err = string_append(&str, "\r\n"); } while (0); if (err) { string_clear(&str); return nerr_pass(err); } cgiwrap_write(str.buf, str.len); string_clear(&str); return STATUS_OK; } /* This will actually issue up to three set cookies, attempting to clear * the damn thing. */ NEOERR *cgi_cookie_clear (CGI *cgi, const char *name, const char *domain, const char *path) { if (path == NULL) path = "/"; if (domain) { if (domain[0] == '.') { cgiwrap_writef ("Set-Cookie: %s=; path=%s; domain=%s;" "expires=Thursday, 01-Jan-1970 00:00:00 GMT\r\n", name, path, domain + 1); } cgiwrap_writef("Set-Cookie: %s=; path=%s; domain=%s;" "expires=Thursday, 01-Jan-1970 00:00:00 GMT\r\n", name, path, domain); } cgiwrap_writef("Set-Cookie: %s=; path=%s; " "expires=Thursday, 01-Jan-1970 00:00:00 GMT\r\n", name, path); return STATUS_OK; } clearsilver-0.10.5/cgi/cgi.h0000644001211700116100000004751510645311613012515 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __CGI_H_ #define __CGI_H_ 1 #include #include "util/neo_err.h" #include "util/neo_hdf.h" #include "cs/cs.h" __BEGIN_DECLS extern NERR_TYPE CGIFinished; extern NERR_TYPE CGIUploadCancelled; extern NERR_TYPE CGIParseNotHandled; /* HACK: Set this value if you want to treat empty CGI Query variables as * non-existant. */ extern int IgnoreEmptyFormVars; typedef struct _cgi CGI; typedef int (*UPLOAD_CB)(CGI *, int nread, int expected); typedef NEOERR* (*CGI_PARSE_CB)(CGI *, char *method, char *ctype, void *rock); struct _cgi_parse_cb { char *method; int any_method; char *ctype; int any_ctype; void *rock; CGI_PARSE_CB parse_cb; struct _cgi_parse_cb *next; }; struct _cgi { /* Only public parts of this structure */ void *data; /* you can store your own information here */ HDF *hdf; /* the HDF dataset associated with this CGI */ BOOL ignore_empty_form_vars; UPLOAD_CB upload_cb; int data_expected; int data_read; struct _cgi_parse_cb *parse_callbacks; /* For line oriented reading of form-data input. Used during cgi_init * only */ char *buf; int buflen; int readlen; BOOL found_nl; BOOL unget; char *last_start; int last_length; int nl; /* this is a list of filepointers pointing at files that were uploaded */ /* Use cgi_filehandle to access these */ ULIST *files; /* By default, cgi_parse unlinks uploaded files as it opens them. */ /* If Config.Upload.Unlink is set to 0, the files are not unlinked */ /* and there names are stored in this list. */ /* Use Query.*.FileName to access these */ ULIST *filenames; /* keep track of the time between cgi_init and cgi_render */ double time_start; double time_end; }; /* * Function: cgi_init - Initialize ClearSilver CGI environment * Description: cgi_init initializes the ClearSilver CGI environment, * including creating the HDF data set. It will then import * the standard CGI environment variables into that dataset, * will parse the QUERY_STRING into the data set, and parse * the HTTP_COOKIE into the data set. Note that if the * var xdisplay is in the form data, cgi_init will attempt * to validate the value and launch the configured debugger * on the CGI program. These variables have to be * specified in the hdf_file pointed to by hdf_file. The * default settings do not allow debugger launching for * security reasons. * Input: cgi - a pointer to a CGI pointer * hdf_file - the path to an HDF data set file that will also be * loaded into the dataset. This will likely have to * a be a full path, as the HDF search paths are not * yet set up. Certain things, like * Output: cgi - an allocated CGI struct, including * Return: NERR_PARSE - parse error in CGI input * NERR_NOMEM - unable to allocate memory * NERR_NOT_FOUND - hdf_file doesn't exist */ NEOERR *cgi_init (CGI **cgi, HDF *hdf); /* * Function: cgi_parse - Parse incoming CGI data * Description: We split cgi_init into two sections, one that parses * just the basics, and the second is cgi_parse. cgi_parse * is responsible for parsing the entity body of the HTTP * request. This payload is typically only sent (expected) * on POST/PUT requests, but generally this is called on * all incoming requests. This function walks the list of * registered parse callbacks (see cgi_register_parse_cb), * and if none of those matches or handles the request, it * falls back to the builtin handlers: * POST w/ application/x-www-form-urlencoded * POST w/ application/form-data * PUT w/ any content type * In general, if there is no Content-Length, then * cgi_parse ignores the payload and doesn't raise an * error. * Input: cgi - a pointer to a CGI pointer * Output: Either data populated into files and cgi->hdf, or whatever * other side effects of your own registered callbacks. * Return: NERR_PARSE - parse error in CGI input * NERR_NOMEM - unable to allocate memory * NERR_NOT_FOUND - hdf_file doesn't exist * NERR_IO - error reading HDF file or reading CGI stdin, or * writing data on multipart/form-data file submission * Anything else you raise. */ NEOERR *cgi_parse (CGI *cgi); /* * Function: cgi_register_parse_cb - Register a parse callback * Description: The ClearSilver CGI Kit has built-in functionality to handle * the following methods: * GET -> doesn't have any data except query string, which * is processed for all methods * POST w/ application/x-www-form-urlencoded * POST w/ multipart/form-data * processed as RFC2388 data into files and HDF (see * cgi_filehandle()) * PUT (any type) * The entire data chunk is stored as a file, with meta * data in HDF (similar to single files in RFC2388). * The data is accessible via cgi_filehandle with NULL * for name. * To handle other methods/content types, you have to * register your own parse function. This isn't necessary * if you aren't expecting any data, and technically HTTP * only allows data on PUT/POST requests (and presumably * user defined methods). In particular, if you want to * implement XML-RPC or SOAP, you'll have to register a * callback here to grab the XML data chunk. Usually * you'll want to register POST w/ application/xml or POST * w/ text/xml (you either need to register both or * register POST w/ * and check the ctype yourself, * remember to nerr_raise(CGIParseNotHandled) if you aren't * handling the POST). * In general, your callback should: * Find out how much data is available: * l = hdf_get_value (cgi->hdf, "CGI.ContentLength", NULL); * len = atoi(l); * And read/handle all of the data using cgiwrap_read. * See the builtin handlers for how this is done. Note * that cgiwrap_read is not guarunteed to return all of * the data you request (just like fread(3)) since it * might be reading of a socket. Sorry. * You should be careful when reading the data to watch * for short reads (ie, end of file) and cases where the * client sends you data ad infinitum. * Input: cgi - a CGI struct * method - the HTTP method you want to handle, or * for all * ctype - the HTTP Content-Type you want to handle, or * for all * rock - opaque data that we'll pass to your call back * Output: None * Return: CGIParseNotHandled if your callback doesn't want to handle * this. This causes cgi_parse to continue walking the list of * callbacks. * */ NEOERR *cgi_register_parse_cb(CGI *cgi, const char *method, const char *ctype, void *rock, CGI_PARSE_CB parse_cb); /* * Function: cgi_destroy - deallocate the data associated with a CGI * Description: cgi_destroy will destroy all the data associated with a * CGI, which mostly means the associated HDF and removal * of any files that were uploaded via multipart/form-data. * (Note that even in the event of a crash, these files * will be deleted, as they were unlinked on creation and * only exist because of the open file pointer) * Input: cgi - a pointer to a pointer to a CGI struct * Output: cgi - NULL on output * Return: None */ void cgi_destroy (CGI **cgi); /* * Function: cgi_cs_init - initialize CS parser with the CGI defaults * Description: cgi_cs_init initializes a CS parser with the CGI HDF * context, and registers the standard CGI filters * Input: cgi - a pointer a CGI struct allocated with cgi_init * cs - a pointer to a CS struct pointer * Output: cs - the allocated/initialized CS struct * Return: NERR_NOMEM - no memory was available to render the template */ NEOERR *cgi_cs_init(CGI *cgi, CSPARSE **cs); /* * Function: cgi_display - render and display the CGI output to the user * Description: cgi_display will render the CS template pointed to by * cs_file using the CGI's HDF data set, and send the * output to the user. Note that the output is actually * rendered into memory first. * Input: cgi - a pointer a CGI struct allocated with cgi_init * cs_file - a ClearSilver template file * Output: None * Return: NERR_IO - an IO error occured during output * NERR_NOMEM - no memory was available to render the template */ NEOERR *cgi_display (CGI *cgi, const char *cs_file); /* * Function: cgi_output - display the CGI output to the user * Description: Normally, this is called by cgi_display, but some * people wanted it external so they could call it * directly. * Input: cgi - a pointer a CGI struct allocated with cgi_init * output - the data to send to output from the CGI * Output: None * Return: NERR_IO - an IO error occured during output * NERR_NOMEM - no memory was available to render the template */ NEOERR *cgi_output (CGI *cgi, STRING *output); /* * Function: cgi_filehandle - return a file pointer to an uploaded file * Description: cgi_filehandle will return the stdio FILE pointer * associated with a file that was uploaded using * multipart/form-data. The FILE pointer is positioned at * the start of the file when first available. * Input: cgi - a pointer to a CGI struct allocated with cgi_init * form_name - the form name that the file was uploaded as * (not the filename) (if NULL, we're asking for the * file handle for the PUT upload) * Output: None * Return: A stdio FILE pointer, or NULL if an error occurs (usually * indicates that the form_name wasn't found, but might indicate * a problem with the HDF dataset) */ FILE *cgi_filehandle (CGI *cgi, const char *form_name); /* * Function: cgi_neo_error - display a NEOERR call backtrace * Description: cgi_neo_error will output a 500 error containing the * NEOERR call backtrace. This function is likely to be * removed from future versions in favor of some sort of * user error mechanism. * Input: cgi - a pointer to a CGI struct * err - a NEOERR (see util/neo_err.h for details) * Output: None * Return: None */ void cgi_neo_error (CGI *cgi, NEOERR *err); /* * Function: cgi_error - display an error string to the user * Description: cgi_error will output a 500 error containing the * specified error message. This function is likely to be * removed from future versions in favor of a user error * mechanism. * Input: cgi - a pointer to a CGI struct * fmt - printf style format string and arguments * Output: None * Return: None */ void cgi_error (CGI *cgi, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); /* * Function: cgi_debug_init - initialize standalone debugging * Description: cgi_debug_init initializes a CGI program for standalone * debugging. By running a ClearSilver CGI program with a * filename on the command line as the first argument, the * CGI program will load that file of the form K=V as a set * of HTTP/CGI environment variables. This allows you to * run the program under a debugger in a reproducible * environment. * Input: argc/argv - the arguments from main * Output: None * Return: None */ void cgi_debug_init (int argc, char **argv); /* * Function: cgi_url_escape - url escape a string * Description: cgi_url_escape will do URL escaping on the passed in * string, and return a newly allocated string that is escaped. * Characters which are escaped include control characters, * %, ?, +, space, =, &, /, and " * Input: buf - a 0 terminated string * Output: esc - a newly allocated string * Return: NERR_NOMEM - no memory available to allocate the escaped string */ NEOERR *cgi_url_escape (const char *buf, char **esc); /* * Function: cgi_url_escape_more - url escape a string * Description: cgi_url_escape_more will do URL escaping on the passed in * string, and return a newly allocated string that is escaped. * Characters which are escaped include control characters, * %, ?, +, space, =, &, /, and " and any characters in * other * Input: buf - a 0 terminated string * other - a 0 terminated string of characters to escape * Output: esc - a newly allocated string * Return: NERR_NOMEM - no memory available to allocate the escaped string */ NEOERR *cgi_url_escape_more (const char *buf, char **esc, const char *other); /* * Function: cgi_url_validate - validate that url is of an allowed format * Description: cgi_url_validate will check that a URL starts with * one of the accepted safe schemes. * If not, it returns "#" as a safe substitute. * Currently accepted schemes are http, https, ftp and mailto. * It then html escapes the entire URL so that it is safe to * insert in an href attribute. * Input: buf - a 0 terminated string * Output: esc - a newly allocated string * Return: NERR_NOMEM - no memory available to allocate the escaped string */ NEOERR *cgi_url_validate (const char *buf, char **esc); /* * Function: cgi_url_unescape - unescape an url encoded string * Description: cgi_url_unescape will do URL unescaping on the passed in * string. This function modifies the string in place * This function will decode any %XX character, and will * decode + as space * Input: buf - a 0 terminated string * Return: pointer to same buf */ char *cgi_url_unescape (char *buf); /* * Function: cgi_redirect - send an HTTP 302 redirect response * Description: cgi_redirect will redirect the user to another page on * your site. This version takes only the path portion of * the URL. As with all printf style commands, you should * not call this with arbitrary input that may contain % * characters, if you are forwarding something directly, * use a format like cgi_redirect (cgi, "%s", buf) * Input: cgi - cgi struct * fmt - printf style format with args * Output: None * Return: None */ void cgi_redirect (CGI *cgi, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); /* * Function: cgi_redirect_uri - send an HTTP 302 redirect response * Description: cgi_redirect_uri will redirect the user to another page on * your site. This version takes the full URL, including * protocol/domain/port/path. * As with all printf style commands, you should * not call this with arbitrary input that may contain % * characters, if you are forwarding something directly, * use a format like cgi_redirect (cgi, "%s", buf) * Input: cgi - cgi struct * fmt - printf style format with args * Output: None * Return: None */ void cgi_redirect_uri (CGI *cgi, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); /* * Function: cgi_vredirect - send an HTTP 302 redirect response * Description: cgi_vredirect is mostly used internally, but can be used * if you need a varargs version of the function. * Input: cgi - cgi struct * uri - whether the URL is full (1) or path only (0) * fmt - printf format string * ap - stdarg va_list * Output: None * Return: None */ void cgi_vredirect (CGI *cgi, int uri, const char *fmt, va_list ap); /* * Function: cgi_cookie_authority - determine the cookie authority for a * domain * Description: cgi_cookie_authority will walk the CookieAuthority * portion of the CGI HDF data set, and return the matching * domain if it exists. The purpose of this is so that you * set domain specific cookies. For instance, you might * have * CookieAuthority.0 = neotonic.com * In which case, any webserver using a hostname ending in * neotonic.com will generate a cookie authority of * neotonic.com. * Input: cgi - a CGI struct * host - optional host to match against. If NULL, the function * will use the HTTP.Host HDF variable. * Output: None * Return: The authority domain, or NULL if none found. */ char *cgi_cookie_authority (CGI *cgi, const char *host); /* * Function: cgi_cookie_set - Set a browser Cookie * Description: cgi_cookie_set will issue a Set-Cookie header that * should cause a browser to return a cookie when required. * Note this function does no escaping of anything, you * have to take care of that first. * Input: cgi - a CGI struct * name - the name of the cookie * value - the value to set the cookie to. * path - optional path for which the cookie is valid. Default * is / * domain - optional domain for which the cookie is valid. You * can use cgi_cookie_authority to determine this * domain. Default is none, which is interpreted by * the browser as the sending domain only. * time_str - expiration time string in the following format * Wdy, DD-Mon-YYYY HH:MM:SS GMT. Only used if * persistent. Default is one year from time of call. * persistent - cookie will be stored by the browser between sessions * secure - cookie will only be sent over secure connections * Output: None * Return: NERR_IO */ NEOERR *cgi_cookie_set (CGI *cgi, const char *name, const char *value, const char *path, const char *domain, const char *time_str, int persistent, int secure); /* * Function: cgi_cookie_clear - clear browser cookie * Description: cgi_cookie_clear will send back a Set-Cookie string that * will attempt to stop a browser from continuing to send * back a cookie. Note that the cookie has to match in * name, domain, and path, and the luck of the Irish has to * be with you for this work all the time, but at the least * it will make the browser send back a cookie with no * value, which the ClearSilver cookie parsing code will * ignore. * Input: cgi - a CGI struct * name - the cookie name to clear * domain - the domain to clear, NULL for none * path - the cookie's path * Output: None * Return: NERR_IO */ NEOERR *cgi_cookie_clear (CGI *cgi, const char *name, const char *domain, const char *path); /* not documented *yet* */ NEOERR *cgi_text_html_strfunc(const char *str, char **ret); NEOERR *cgi_html_strip_strfunc(const char *str, char **ret); NEOERR *cgi_html_escape_strfunc(const char *str, char **ret); NEOERR *cgi_js_escape (const char *buf, char **esc); void cgi_html_ws_strip(STRING *str, int level); NEOERR *cgi_register_strfuncs(CSPARSE *cs); /* internal use only */ NEOERR * parse_rfc2388 (CGI *cgi); NEOERR * open_upload(CGI *cgi, int unlink_files, FILE **fpw); __END_DECLS #endif /* __CGI_H_ */ clearsilver-0.10.5/cgi/cgi_cstest.c0000644001211700116100000000354610370021321014056 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "ClearSilver.h" #include #include static NEOERR *output (void *ctx, char *s) { printf ("%s", s); return STATUS_OK; } int main (int argc, char *argv[]) { NEOERR *err; CSPARSE *parse; HDF *hdf; int verbose = 0; char *hdf_file, *cs_file; if (argc < 3) { ne_warn ("Usage: cstest [-v] "); return -1; } if (!strcmp(argv[1], "-v")) { verbose = 1; if (argc < 4) { ne_warn ("Usage: cstest [-v] "); return -1; } hdf_file = argv[2]; cs_file = argv[3]; } else { hdf_file = argv[1]; cs_file = argv[2]; } err = hdf_init(&hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = hdf_read_file(hdf, hdf_file); if (err != STATUS_OK) { nerr_log_error(err); return -1; } printf ("Parsing %s\n", cs_file); err = cs_init (&parse, hdf); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = cgi_register_strfuncs(parse); if (err != STATUS_OK) { nerr_log_error(err); return -1; } err = cs_parse_file (parse, cs_file); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } err = cs_render(parse, NULL, output); if (err != STATUS_OK) { err = nerr_pass(err); nerr_log_error(err); return -1; } if (verbose) { printf ("\n-----------------------\nCS DUMP\n"); err = cs_dump(parse, NULL, output); } cs_destroy (&parse); if (verbose) { printf ("\n-----------------------\nHDF DUMP\n"); hdf_dump (hdf, NULL); } hdf_destroy(&hdf); return 0; } clearsilver-0.10.5/cgi/cgiwrap.c0000644001211700116100000001452210541666104013375 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #if HAVE_FEATURES_H #include #endif #include #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "cgi/cgiwrap.h" typedef struct _cgiwrapper { int argc; char **argv; char **envp; int env_count; READ_FUNC read_cb; WRITEF_FUNC writef_cb; WRITE_FUNC write_cb; GETENV_FUNC getenv_cb; PUTENV_FUNC putenv_cb; ITERENV_FUNC iterenv_cb; void *data; int emu_init; } CGIWRAPPER; static CGIWRAPPER GlobalWrapper = {0, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0}; void cgiwrap_init_std (int argc, char **argv, char **envp) { /* Allow setting of these even after cgiwrap_init_emu is called */ GlobalWrapper.argc = argc; GlobalWrapper.argv = argv; GlobalWrapper.envp = envp; GlobalWrapper.env_count = 0; while (envp[GlobalWrapper.env_count] != NULL) GlobalWrapper.env_count++; /* so you can compile the same code for embedded without mods. * Note that this setting is global for the lifetime of the program, so * you can never reset these values after calling cgiwrap_init_emu by * calling cgiwrap_init_std, you'll have to call cgiwrap_init_emu with NULL * values to reset */ if (GlobalWrapper.emu_init) return; GlobalWrapper.read_cb = NULL; GlobalWrapper.writef_cb = NULL; GlobalWrapper.write_cb = NULL; GlobalWrapper.getenv_cb = NULL; GlobalWrapper.putenv_cb = NULL; GlobalWrapper.iterenv_cb = NULL; GlobalWrapper.data = NULL; } void cgiwrap_init_emu (void *data, READ_FUNC read_cb, WRITEF_FUNC writef_cb, WRITE_FUNC write_cb, GETENV_FUNC getenv_cb, PUTENV_FUNC putenv_cb, ITERENV_FUNC iterenv_cb) { /* leave argc, argv, envp, env_count alone since we either don't use them, or * they are used by the default versions if any of these are passed as NULL. * Note that means that if you pass NULL for anything here, you'd better * have called cgiwrap_init_std first! */ GlobalWrapper.data = data; GlobalWrapper.read_cb = read_cb; GlobalWrapper.writef_cb = writef_cb; GlobalWrapper.write_cb = write_cb; GlobalWrapper.getenv_cb = getenv_cb; GlobalWrapper.putenv_cb = putenv_cb; GlobalWrapper.iterenv_cb = iterenv_cb; GlobalWrapper.emu_init = 1; } NEOERR *cgiwrap_getenv (const char *k, char **v) { if (GlobalWrapper.getenv_cb != NULL) { *v = GlobalWrapper.getenv_cb (GlobalWrapper.data, k); } else { char *s = getenv(k); if (s != NULL) { *v = strdup(s); if (*v == NULL) { return nerr_raise (NERR_NOMEM, "Unable to duplicate env var %s=%s", k, s); } } else { *v = NULL; } } return STATUS_OK; } NEOERR *cgiwrap_putenv (const char *k, const char *v) { if (GlobalWrapper.putenv_cb != NULL) { if (GlobalWrapper.putenv_cb(GlobalWrapper.data, k, v)) return nerr_raise(NERR_NOMEM, "putenv_cb says nomem when %s=%s", k, v); } else { char *buf; int l; l = strlen(k) + strlen(v) + 2; buf = (char *) malloc(sizeof(char) * l); if (buf == NULL) return nerr_raise(NERR_NOMEM, "Unable to allocate memory for putenv %s=%s", k, v); snprintf (buf, l, "%s=%s", k, v); if (putenv (buf)) return nerr_raise(NERR_NOMEM, "putenv says nomem when %s", buf); } return STATUS_OK; } NEOERR *cgiwrap_iterenv (int num, char **k, char **v) { *k = NULL; *v = NULL; if (GlobalWrapper.iterenv_cb != NULL) { int r; r = GlobalWrapper.iterenv_cb(GlobalWrapper.data, num, k, v); if (r) return nerr_raise(NERR_SYSTEM, "iterenv_cb returned %d", r); } else if (GlobalWrapper.envp != NULL && num < GlobalWrapper.env_count) { char *c, *s = GlobalWrapper.envp[num]; c = strchr (s, '='); if (c == NULL) return STATUS_OK; *c = '\0'; *k = strdup(s); *c = '='; if (*k == NULL) return nerr_raise(NERR_NOMEM, "iterenv says nomem for %s", s); *v = strdup(c+1); if (*v == NULL) { free(*k); *k = NULL; return nerr_raise(NERR_NOMEM, "iterenv says nomem for %s", s); } } return STATUS_OK; } NEOERR *cgiwrap_writef (const char *fmt, ...) { va_list ap; va_start (ap, fmt); cgiwrap_writevf (fmt, ap); va_end (ap); return STATUS_OK; } NEOERR *cgiwrap_writevf (const char *fmt, va_list ap) { int r; if (GlobalWrapper.writef_cb != NULL) { r = GlobalWrapper.writef_cb (GlobalWrapper.data, fmt, ap); if (r) return nerr_raise_errno (NERR_IO, "writef_cb returned %d", r); } else { vprintf (fmt, ap); /* vfprintf(stderr, fmt, ap); */ } return STATUS_OK; } NEOERR *cgiwrap_write (const char *buf, int buf_len) { int r; if (GlobalWrapper.write_cb != NULL) { r = GlobalWrapper.write_cb (GlobalWrapper.data, buf, buf_len); if (r != buf_len) return nerr_raise_errno (NERR_IO, "write_cb returned %d<%d", r, buf_len); } else { /* r = fwrite(buf, sizeof(char), buf_len, stderr); */ r = fwrite(buf, sizeof(char), buf_len, stdout); if (r != buf_len) return nerr_raise_errno (NERR_IO, "fwrite returned %d<%d", r, buf_len); } return STATUS_OK; } void cgiwrap_read (char *buf, int buf_len, int *read_len) { if (GlobalWrapper.read_cb != NULL) { *read_len = GlobalWrapper.read_cb (GlobalWrapper.data, buf, buf_len); } else { #ifdef __UCLIBC__ /* According to * http://cvs.uclinux.org/cgi-bin/cvsweb.cgi/uClibc/libc/stdio/stdio.c#rev1.28 * Note: there is a difference in behavior between glibc and uClibc here * regarding fread() on a tty stream. glibc's fread() seems to return * after reading all _available_ data even if not at end-of-file, while * uClibc's fread() continues reading until all requested or eof or error. * The latter behavior seems correct w.r.t. the standards. * * So, we use read on uClibc. This may be required on other platforms as * well. Using raw and buffered i/o interchangeably can be problematic, * but everyone should be going through the cgiwrap interfaces which only * provide this one read function. */ *read_len = read (fileno(stdin), buf, buf_len); #else *read_len = fread (buf, sizeof(char), buf_len, stdin); #endif } } clearsilver-0.10.5/cgi/cgiwrap.h0000644001211700116100000001465510645311624013410 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* * cgiwrap.h * The purpose of the cgiwrap is to abstract the CGI interface to allow * for other than the default implementation. The default * implementation is of course based on environment variables and stdio, * but this can be used with server modules which can substitute their * own implementation of these functions. */ #ifndef __CGIWRAP_H_ #define __CGIWRAP_H_ 1 #include #include "util/neo_err.h" __BEGIN_DECLS typedef int (*READ_FUNC)(void *, char *, int); typedef int (*WRITEF_FUNC)(void *, const char *, va_list); typedef int (*WRITE_FUNC)(void *, const char *, int); typedef char *(*GETENV_FUNC)(void *, const char *); typedef int (*PUTENV_FUNC)(void *, const char *, const char *); typedef int (*ITERENV_FUNC)(void *, int, char **, char **); /* * Function: cgiwrap_init_std - Initialize cgiwrap with default functions * Description: cgiwrap_init_std will initialize the cgiwrap subsystem * to use the default CGI functions, ie * getenv/putenv/stdio. In reality, all this is doing is * setting up the data for the cgiwrap_iterenv() function. * Input: the arguments to main, namely argc/argv/envp * Output: None * Returns: None */ void cgiwrap_init_std (int argc, char **argv, char **envp); /* * Function: cgiwrap_init_emu - initialize cgiwrap for emulated use * Description: cgiwrap_init_emu sets up the cgiwrap subsystem for use * in an emulated environment where you are providing * routines to use in place of the standard routines, ie * when used to interface with a server or scripting * language. * See cgi/cgiwrap.h for the exact definitions of the * callback functions. * Input: data - user data to be passed to the specified callbacks * read_cb - a cb to replace fread(stdin) * writef_cb - a cb to repalce fprintf(stdout) * write_cb - a cb to replace fwrite(stdout) * getenv_cb - a cb to replace getenv * putenv_cb - a cb to replace putenv * iterenv_cb - a cb to replace the default environment iteration * function (which just wraps walking the envp array) * Output: None * Returns: None */ void cgiwrap_init_emu (void *data, READ_FUNC read_cb, WRITEF_FUNC writef_cb, WRITE_FUNC write_cb, GETENV_FUNC getenv_cb, PUTENV_FUNC putenv_cb, ITERENV_FUNC iterenv_cb); /* * Function: cgiwrap_getenv - the wrapper for getenv * Description: cgiwrap_getenv wraps the getenv function for access to * environment variables, which are used to pass data to * CGI scripts. This version differs from the system * getenv in that it makes a copy of the value it returns, * which gets around problems when wrapping this routine in * garbage collected/reference counted languages by * moving the ownership of the data to the calling * function. * Input: k - the environment variable to lookup * Output: v - a newly allocated copy of the value of that variable, or * NULL if not found. * Returns: NERR_NOMEM if there isn't memory available to allocate the result */ NEOERR *cgiwrap_getenv (const char *k, char **v); /* * Function: cgiwrap_putenv - wrap the putenv call * Description: cgiwrap_putenv wraps the putenv call. This is mostly * used by the cgi_debug_init function to create an * artificial environment. This version differs from the * system version by having separate arguments for the * variable name and value, which makes life easier for the * caller (usually), and keeps most wrapping callbacks from * having to implement a parser to separate them. * Input: k - the env var name * v - the new value for env var k * Output: None * Returns: NERR_NOMEM */ NEOERR *cgiwrap_putenv (const char *k, const char *v); /* * Function: cgiwrap_iterenv - iterater for env vars * Description: cgiwrap_iterenv allows a program to iterate over all the * environment variables. This is probably mostly used by * the default debug output. * Input: n - variable to return. This should start at 0 and increment * until you receive a NULL return value. * Output: k - a malloc'd copy of the variable name * v - a malloc'd copy of the variable value * Returns: NERR_NOMEM */ NEOERR *cgiwrap_iterenv (int n, char **k, char **v); /* * Function: cgiwrap_writef - a wrapper for printf * Description: cgiwrap_writef is the formatted output command that * replaces printf or fprintf(stdout) in a standard CGI * Input: fmt - standard printf fmt string and args * Output: None * Returns: NERR_SYSTEM */ NEOERR *cgiwrap_writef (const char *fmt, ...) ATTRIBUTE_PRINTF(1,2); /* * Function: cgiwrap_writevf - a wrapper for vprintf * Description: cgiwrap_writevf is the formatted output command that * replaces vprintf or fvprintf(stdout) in a standard CGI * It is also used by cgiwrap_writef (the actual wrapped * function is a v type function) * Input: fmt - standard printf fmt string * ap - stdarg argument pointer * Output: None * Returns: NERR_SYSTEM */ NEOERR *cgiwrap_writevf (const char *fmt, va_list ap); /* * Function: cgiwrap_write - wrapper for the fwrite(stdout) * Description: cgiwrap_write is the block data output function for * cgiwrap that replaces fwrite(stdout) in regular CGIs * Input: buf - a character buffer * buf_len - the length of the buffer in buf * Output: None * Returns: NERR_IO */ NEOERR *cgiwrap_write (const char *buf, int buf_len); /* * Function: cgiwrap_read - cgiwrap input function * Description: cgiwrap_read is used to read incoming data from the * client, usually from a POST or PUT HTTP request. It * wraps the part of fread(stdin). * Input: buf - a pre-allocated buffer to read the data into * buf_len - the size of the pre-allocated buffer * Output: read_len - the number of bytes read into buf * Returns: None */ void cgiwrap_read (char *buf, int buf_len, int *read_len); __END_DECLS #endif /* __CGIWRAP_H_ */ clearsilver-0.10.5/cgi/date.c0000644001211700116100000001072010522672266012657 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_hdf.h" #include "util/neo_date.h" #include "cgi.h" #include "date.h" /* * prefix.sec * prefix.min * prefix.hour - 12 hour * prefix.am - 1 if AM * prefix.24hour - 24 hour * prefix.mday * prefix.mon - numeric month * prefix.year - full year (ie, 4 digits) * prefix.2yr - year (2 digits) * prefix.wday - day of the week * prefix.tzoffset - hhmm from UTC * */ NEOERR *export_date_tm (HDF *data, const char *prefix, struct tm *ttm) { NEOERR *err; HDF *obj; int hour, am = 1; char buf[256]; int tzoffset_seconds = 0; int tzoffset = 0; char tzsign = '+'; obj = hdf_get_obj (data, prefix); if (obj == NULL) { err = hdf_set_value (data, prefix, ""); if (err) return nerr_pass(err); obj = hdf_get_obj (data, prefix); } snprintf (buf, sizeof(buf), "%02d", ttm->tm_sec); err = hdf_set_value (obj, "sec", buf); if (err) return nerr_pass(err); snprintf (buf, sizeof(buf), "%02d", ttm->tm_min); err = hdf_set_value (obj, "min", buf); if (err) return nerr_pass(err); snprintf (buf, sizeof(buf), "%02d", ttm->tm_hour); err = hdf_set_value (obj, "24hour", buf); if (err) return nerr_pass(err); hour = ttm->tm_hour; if (hour == 0) { hour = 12; } else if (hour == 12) { am = 0; } else if (hour > 12) { am = 0; hour -= 12; } err = hdf_set_int_value (obj, "hour", hour); if (err) return nerr_pass(err); err = hdf_set_int_value (obj, "am", am); if (err) return nerr_pass(err); err = hdf_set_int_value (obj, "mday", ttm->tm_mday); if (err) return nerr_pass(err); err = hdf_set_int_value (obj, "mon", ttm->tm_mon + 1); if (err) return nerr_pass(err); err = hdf_set_int_value (obj, "year", ttm->tm_year + 1900); if (err) return nerr_pass(err); snprintf(buf, sizeof(buf), "%02d", ttm->tm_year % 100); err = hdf_set_value (obj, "2yr", buf); if (err) return nerr_pass(err); err = hdf_set_int_value (obj, "wday", ttm->tm_wday); if (err) return nerr_pass(err); // neo_tz_offset() returns offset from GMT in seconds tzoffset_seconds = neo_tz_offset(ttm); tzoffset = tzoffset_seconds / 60; if (tzoffset < 0) { tzoffset *= -1; tzsign = '-'; } snprintf(buf, sizeof(buf), "%c%02d%02d", tzsign, tzoffset / 60, tzoffset % 60); err = hdf_set_value (obj, "tzoffset", buf); if (err) return nerr_pass(err); return STATUS_OK; } NEOERR *export_date_time_t (HDF *data, const char *prefix, const char *timezone, time_t tt) { struct tm ttm; neo_time_expand (tt, timezone, &ttm); return nerr_pass (export_date_tm (data, prefix, &ttm)); } /* from httpd util.c : made infamous with Roy owes Rob beer. */ static char *months[] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; int find_month(char *mon) { register int x; for(x=0;x<12;x++) if(!strcmp(months[x],mon)) return x; return -1; } int later_than(struct tm *lms, char *ims) { char *ip; char mname[256]; int year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0, x; /* Whatever format we're looking at, it will start * with weekday. */ /* Skip to first space. */ if(!(ip = strchr(ims,' '))) return 0; else while(isspace(*ip)) ++ip; if(isalpha(*ip)) { /* ctime */ sscanf(ip,"%25s %d %d:%d:%d %d",mname,&day,&hour,&min,&sec,&year); } else if(ip[2] == '-') { /* RFC 850 (normal HTTP) */ char t[256]; sscanf(ip,"%s %d:%d:%d",t,&hour,&min,&sec); t[2] = '\0'; day = atoi(t); t[6] = '\0'; strcpy(mname,&t[3]); x = atoi(&t[7]); /* Prevent * wraparound * from * ambiguity * */ if(x < 70) x += 100; year = 1900 + x; } else { /* RFC 822 */ sscanf(ip,"%d %s %d %d:%d:%d",&day,mname,&year,&hour,&min,&sec); } month = find_month(mname); if((x = (1900+lms->tm_year) - year)) return x < 0; if((x = lms->tm_mon - month)) return x < 0; if((x = lms->tm_mday - day)) return x < 0; if((x = lms->tm_hour - hour)) return x < 0; if((x = lms->tm_min - min)) return x < 0; if((x = lms->tm_sec - sec)) return x < 0; return 1; } clearsilver-0.10.5/cgi/date.h0000644001211700116100000000102110261115232012637 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __DATE_H_ #define __DATE_H_ 1 #include __BEGIN_DECLS NEOERR *export_date_tm (HDF *obj, const char *prefix, struct tm *ttm); NEOERR *export_date_time_t (HDF *obj, const char *prefix, const char *timezone, time_t tt); __END_DECLS #endif /* __DATE_H_ */ clearsilver-0.10.5/cgi/fcgi_hello.c0000644001211700116100000000271110643275546014042 00000000000000/** * Copyright 2006 Mike Tsao. All rights reserved. * * Hello World using FastCGI and ClearSilver. */ #include "ClearSilver.h" #include #include #include #include #include static bool quit = false; static int cs_printf(void *ctx, const char *s, va_list args) { return printf(s, args); } static int cs_write(void *ctx, const char *s, int n) { return fwrite(const_cast(s), n, 1, FCGI_stdout); } int main(int argc, char **argv, char **envp) { openlog(argv[0], 0, LOG_USER); syslog(LOG_INFO, "%s started.", argv[0]); int hits = 0; while (FCGI_Accept() >= 0) { HDF *hdf = NULL; CGI *cgi = NULL; /* Note that we aren't doing any error handling here, we really should. */ hdf_init(&hdf); // Takes ownership of HDF. cgi_init(&cgi, hdf); hits++; /* Initialize the standard cgiwrap environment. FastCGI already wraps some * of the standard calls that cgiwrap wraps. */ cgiwrap_init_std(argc, argv, environ); /* Then, we install our own wrappers for some cgiwrap calls that aren't * already wrapped in the standard wrappers. */ cgiwrap_init_emu(NULL, NULL, cs_printf, cs_write, NULL, NULL, NULL); hdf_read_file(cgi->hdf, "common.hdf"); hdf_read_file(cgi->hdf, "hello_world.hdf"); cgi_display(cgi, "hello_world.cs"); // This destroys HDF. cgi_destroy(&cgi); } syslog(LOG_INFO, "%s ending.", argv[0]); return 0; } clearsilver-0.10.5/cgi/html.c0000644001211700116100000004307210516004653012704 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include "cs_config.h" #include #include #include #include #include #include "util/neo_misc.h" #include "util/neo_err.h" #include "util/neo_str.h" #include "html.h" #include "cgi.h" static int has_space_formatting(const char *src, int slen) { int spaces = 0; int returns = 0; int ascii_art = 0; int x = 0; for (x = 0; x < slen; x++) { if (src[x] == '\t') return 1; if (src[x] == ' ') { spaces++; if (x && (src[x-1] == '.')) spaces--; } else if (src[x] == '\n') { spaces = 0; returns++; } else if (strchr ("/\\<>:[]!@#$%^&*()|", src[x])) { ascii_art++; if (ascii_art > 3) return 2; } else if (src[x] != '\r') { if (returns > 2) return 1; if (spaces > 2) return 1; returns = 0; spaces = 0; ascii_art = 0; } } return 0; } /* static int has_long_lines (char *s, int l) { char *ptr; int x = 0; while (x < l) { ptr = strchr (s + x, '\n'); if (ptr == NULL) { if (l - x > 75) return 1; return 0; } if (ptr - (s + x) > 75) return 1; x = ptr - s + 1; } return 0; } */ /* The first step is to actually find all of the URLs and email * addresses using our handy regular expressions. We then mark these, * and then go through convert non-special areas with straight * text->html escapes, and convert special parts as special parts */ struct _parts { int begin; int end; int type; }; #define SC_TYPE_TEXT 1 #define SC_TYPE_URL 2 #define SC_TYPE_EMAIL 3 static char *EmailRe = "[^][@:;<>\\\"()[:space:][:cntrl:]]+@[-+a-zA-Z0-9]+\\.[-+a-zA-Z0-9\\.]+[-+a-zA-Z0-9]"; static char *URLRe = "((http|https|ftp|mailto):(//)?[^[:space:]>\"\t]*|www\\.[-a-z0-9\\.]+)[^[:space:];\t\">]*"; static NEOERR *split_and_convert (const char *src, int slen, STRING *out, HTML_CONVERT_OPTS *opts) { NEOERR *err = STATUS_OK; static int compiled = 0; static regex_t email_re, url_re; regmatch_t email_match, url_match; int errcode; char *ptr, *esc; char errbuf[256]; struct _parts *parts; int part_count; int part; int x, i; int spaces = 0; if (!compiled) { if ((errcode = regcomp (&email_re, EmailRe, REG_ICASE | REG_EXTENDED))) { regerror (errcode, &email_re, errbuf, sizeof(errbuf)); return nerr_raise (NERR_PARSE, "Unable to compile EmailRE: %s", errbuf); } if ((errcode = regcomp (&url_re, URLRe, REG_ICASE | REG_EXTENDED))) { regerror (errcode, &url_re, errbuf, sizeof(errbuf)); return nerr_raise (NERR_PARSE, "Unable to compile URLRe: %s", errbuf); } compiled = 1; } part_count = 20; parts = (struct _parts *) malloc (sizeof(struct _parts) * part_count); part = 0; x = 0; if (regexec (&email_re, src+x, 1, &email_match, 0) != 0) { email_match.rm_so = -1; email_match.rm_eo = -1; } else { email_match.rm_so += x; email_match.rm_eo += x; } if (regexec (&url_re, src+x, 1, &url_match, 0) != 0) { url_match.rm_so = -1; url_match.rm_eo = -1; } else { url_match.rm_so += x; url_match.rm_eo += x; } while ((x < slen) && !((email_match.rm_so == -1) && (url_match.rm_so == -1))) { if (part >= part_count) { part_count *= 2; parts = (struct _parts *) realloc (parts, sizeof(struct _parts) * part_count); } if ((url_match.rm_so != -1) && ((email_match.rm_so == -1) || (url_match.rm_so <= email_match.rm_so))) { parts[part].begin = url_match.rm_so; parts[part].end = url_match.rm_eo; parts[part].type = SC_TYPE_URL; x = parts[part].end + 1; part++; if (x < slen) { if (regexec (&url_re, src+x, 1, &url_match, 0) != 0) { url_match.rm_so = -1; url_match.rm_eo = -1; } else { url_match.rm_so += x; url_match.rm_eo += x; } if ((email_match.rm_so != -1) && (x > email_match.rm_so)) { if (regexec (&email_re, src+x, 1, &email_match, 0) != 0) { email_match.rm_so = -1; email_match.rm_eo = -1; } else { email_match.rm_so += x; email_match.rm_eo += x; } } } } else { parts[part].begin = email_match.rm_so; parts[part].end = email_match.rm_eo; parts[part].type = SC_TYPE_EMAIL; x = parts[part].end + 1; part++; if (x < slen) { if (regexec (&email_re, src+x, 1, &email_match, 0) != 0) { email_match.rm_so = -1; email_match.rm_eo = -1; } else { email_match.rm_so += x; email_match.rm_eo += x; } if ((url_match.rm_so != -1) && (x > url_match.rm_so)) { if (regexec (&url_re, src+x, 1, &url_match, 0) != 0) { url_match.rm_so = -1; url_match.rm_eo = -1; } else { url_match.rm_so += x; url_match.rm_eo += x; } } } } } i = 0; x = 0; while (x < slen) { if ((i >= part) || (x < parts[i].begin)) { ptr = strpbrk(src + x, "&<>\r\n "); if (ptr == NULL) { if (spaces) { int sp; for (sp = 0; sp < spaces - 1; sp++) { err = string_append (out, " "); if (err != STATUS_OK) break; } if (err != STATUS_OK) break; err = string_append_char (out, ' '); } spaces = 0; if (i < part) { err = string_appendn (out, src + x, parts[i].begin - x); x = parts[i].begin; } else { err = string_append (out, src + x); x = slen; } } else { if ((i >= part) || ((ptr - src) < parts[i].begin)) { if (spaces) { int sp; for (sp = 0; sp < spaces - 1; sp++) { err = string_append (out, " "); if (err != STATUS_OK) break; } if (err != STATUS_OK) break; err = string_append_char (out, ' '); } spaces = 0; err = string_appendn (out, src + x, (ptr - src) - x); if (err != STATUS_OK) break; x = ptr - src; if (src[x] == ' ') { if (opts->space_convert) { spaces++; } else err = string_append_char (out, ' '); } else { if (src[x] != '\n' && spaces) { int sp; for (sp = 0; sp < spaces - 1; sp++) { err = string_append (out, " "); if (err != STATUS_OK) break; } if (err != STATUS_OK) break; err = string_append_char (out, ' '); } spaces = 0; if (src[x] == '&') err = string_append (out, "&"); else if (src[x] == '<') err = string_append (out, "<"); else if (src[x] == '>') err = string_append (out, ">"); else if (src[x] == '\n') if (opts->newlines_convert) err = string_append (out, "
\n"); else if (x && src[x-1] == '\n') err = string_append (out, "

\n"); else err = string_append_char (out, '\n'); else if (src[x] != '\r') err = nerr_raise (NERR_ASSERT, "src[x] == '%c'", src[x]); } x++; } else { if (spaces) { int sp; for (sp = 0; sp < spaces - 1; sp++) { err = string_append (out, " "); if (err != STATUS_OK) break; } if (err != STATUS_OK) break; err = string_append_char (out, ' '); } spaces = 0; err = string_appendn (out, src + x, parts[i].begin - x); x = parts[i].begin; } } } else { if (spaces) { int sp; for (sp = 0; sp < spaces - 1; sp++) { err = string_append (out, " "); if (err != STATUS_OK) break; } if (err != STATUS_OK) break; err = string_append_char (out, ' '); } spaces = 0; if (parts[i].type == SC_TYPE_URL) { char last_char = src[parts[i].end-1]; int suffix=0; if (last_char == '.' || last_char == ',') { suffix=1; } err = string_append (out, " url_class) { err = string_appendf (out, "class=%s ", opts->url_class); if (err) break; } if (opts->url_target) { err = string_appendf (out, "target=\"%s\" ", opts->url_target); if (err) break; } err = string_append(out, "href=\""); if (err) break; if (opts->bounce_url) { char *url, *esc_url, *new_url; int url_len; if (!strncasecmp(src + x, "www.", 4)) { url_len = 7 + parts[i].end - x - suffix; url = (char *) malloc(url_len+1); if (url == NULL) { err = nerr_raise(NERR_NOMEM, "Unable to allocate memory to convert url"); break; } strcpy(url, "http://"); strncat(url, src + x, parts[i].end - x - suffix); } else { url_len = parts[i].end - x - suffix; url = (char *) malloc(url_len+1); if (url == NULL) { err = nerr_raise(NERR_NOMEM, "Unable to allocate memory to convert url"); break; } strncpy(url, src + x, parts[i].end - x - suffix); url[url_len] = '\0'; } err = cgi_url_escape(url, &esc_url); free(url); if (err) { free(esc_url); break; } new_url = sprintf_alloc(opts->bounce_url, esc_url); free(esc_url); if (new_url == NULL) { err = nerr_raise(NERR_NOMEM, "Unable to allocate memory to convert url"); break; } err = string_append (out, new_url); free(new_url); if (err) break; } else { if (!strncasecmp(src + x, "www.", 4)) { err = string_append (out, "http://"); if (err != STATUS_OK) break; } err = string_appendn (out, src + x, parts[i].end - x - suffix); if (err != STATUS_OK) break; } err = string_append (out, "\">"); if (err != STATUS_OK) break; if (opts->link_name) { err = html_escape_alloc((opts->link_name), strlen(opts->link_name), &esc); } else { err = html_escape_alloc((src + x), parts[i].end - x - suffix, &esc); } if (err != STATUS_OK) break; err = string_append (out, esc); free(esc); if (err != STATUS_OK) break; err = string_append (out, ""); if (suffix) { err = string_appendn(out,src + parts[i].end - 1,1); if (err != STATUS_OK) break; } } else /* type == SC_TYPE_EMAIL */ { err = string_append (out, "mailto_class) { err = string_appendf (out, "class=%s ", opts->mailto_class); if (err) break; } err = string_append(out, "href=\"mailto:"); if (err) break; err = string_appendn (out, src + x, parts[i].end - x); if (err != STATUS_OK) break; err = string_append (out, "\">"); if (err != STATUS_OK) break; err = html_escape_alloc(src + x, parts[i].end - x, &esc); if (err != STATUS_OK) break; err = string_append (out, esc); free(esc); if (err != STATUS_OK) break; err = string_append (out, ""); } x = parts[i].end; i++; } if (err != STATUS_OK) break; } free (parts); return err; } static void strip_white_space_end (STRING *str) { int x = 0; int ol = str->len; char *ptr; int i; while (x < str->len) { ptr = strchr(str->buf + x, '\n'); if (ptr == NULL) { /* just strip the white space at the end of the string */ ol = strlen(str->buf); while (ol && isspace(str->buf[ol-1])) { str->buf[ol - 1] = '\0'; ol--; } str->len = ol; return; } else { x = i = ptr - str->buf; if (x) { x--; while (x && isspace(str->buf[x]) && (str->buf[x] != '\n')) x--; if (x) x++; memmove (str->buf + x, ptr, ol - i + 1); x++; str->len -= ((i - x) + 1); str->buf[str->len] = '\0'; ol = str->len; } } } } NEOERR *convert_text_html_alloc (const char *src, int slen, char **out) { return nerr_pass(convert_text_html_alloc_options(src, slen, out, NULL)); } NEOERR *convert_text_html_alloc_options (const char *src, int slen, char **out, HTML_CONVERT_OPTS *opts) { NEOERR *err; STRING out_s; int formatting = 0; HTML_CONVERT_OPTS my_opts; string_init(&out_s); if (opts == NULL) { opts = &my_opts; opts->bounce_url = NULL; opts->url_class = NULL; opts->url_target = "_blank"; opts->mailto_class = NULL; opts->long_lines = 0; opts->space_convert = 0; opts->newlines_convert = 1; opts->longline_width = 75; /* This hasn't been used in a while, actually */ opts->check_ascii_art = 1; opts->link_name = NULL; } do { if (opts->check_ascii_art) { formatting = has_space_formatting (src, slen); if (formatting) opts->space_convert = 1; } if (formatting == 2) { /* Do

 formatting */
      opts->newlines_convert = 1;
      err = string_append (&out_s, "");
      if (err != STATUS_OK) break;
      err = split_and_convert(src, slen, &out_s, opts);
      if (err != STATUS_OK) break;
      err = string_append (&out_s, "");
      if (err != STATUS_OK) break;
      /* Strip white space at end of lines */
      strip_white_space_end (&out_s);
    }
    else
    {
      /* int nl = has_long_lines (src, slen); */
      err = split_and_convert(src, slen, &out_s, opts);
    }
  } while (0);
  if (err != STATUS_OK)
  {
    string_clear (&out_s);
    return nerr_pass (err);
  }
  if (out_s.buf == NULL)
  {
    *out = strdup("");
  }
  else
  {
    *out = out_s.buf;
  }
  return STATUS_OK;
}

NEOERR *html_escape_alloc (const char *src, int slen,
                           char **out)
{
  return nerr_pass(neos_html_escape(src, slen, out));
}

/* Replace ampersand with iso-8859-1 character code */
static unsigned char _expand_amp_8859_1_char (const char *s)
{
  if (s[0] == '\0')
    return 0;

  switch (s[0]) {
    case '#':
      if (s[1] == 'x') return strtol (s+2, NULL, 16);
      return strtol (s+1, NULL, 10);
    case 'a':
      if (!strcmp(s, "agrave")) return 0xe0; /* à */
      if (!strcmp(s, "aacute")) return 0xe1; /* á */
      if (!strcmp(s, "acirc")) return 0xe2; /* â */
      if (!strcmp(s, "atilde")) return 0xe3; /* ã */
      if (!strcmp(s, "auml")) return 0xe4; /* ä */
      if (!strcmp(s, "aring")) return 0xe5; /* å */
      if (!strcmp(s, "aelig")) return 0xe6; /* æ */
      if (!strcmp(s, "amp")) return '&';
      return 0;
    case 'c':
      if (!strcmp(s, "ccedil")) return 0xe7; /* ç */
      return 0;
    case 'e':
      if (!strcmp(s, "egrave")) return 0xe8; /* è */
      if (!strcmp(s, "eacute")) return 0xe9; /* é */
      if (!strcmp(s, "ecirc")) return 0xea; /* ê */
      if (!strcmp(s, "euml")) return 0xeb; /* ë */
      if (!strcmp(s, "eth")) return 0xf0; /* ð */
      return 0;
    case 'i':
      if (!strcmp(s, "igrave")) return 0xec; /* ì */
      if (!strcmp(s, "iacute")) return 0xed; /* í */
      if (!strcmp(s, "icirc")) return 0xee; /* î */
      if (!strcmp(s, "iuml")) return 0xef; /* ï */
      return 0;
    case 'g':
      if (!strcmp(s, "gt")) return '>';
      return 0;
    case 'l':
      if (!strcmp(s, "lt")) return '<';
      return 0;
    case 'n':
      if (!strcmp(s, "ntilde")) return 0xf1; /* ñ */
      if (!strcmp(s, "nbsp")) return ' ';
      return 0;
    case 'o':
      if (!strcmp(s, "ograve")) return 0xf2; /* ò */
      if (!strcmp(s, "oacute")) return 0xf3; /* ó */
      if (!strcmp(s, "ocirc")) return 0xf4; /* ô */
      if (!strcmp(s, "otilde")) return 0xf5; /* õ */
      if (!strcmp(s, "ouml")) return 0xf6; /* ö */
      if (!strcmp(s, "oslash")) return 0xf8; /* ø */
      return 0;
    case 'q': /* quot */
      if (!strcmp(s, "quot")) return '"';
      return 0;
    case 's':
      if (!strcmp(s, "szlig")) return 0xdf; /* ß */
      return 0;
    case 't':
      if (!strcmp(s, "thorn")) return 0xfe; /* þ */
      return 0;
    case 'u':
      if (!strcmp(s, "ugrave")) return 0xf9; /* ù */
      if (!strcmp(s, "uacute")) return 0xfa; /* ú */
      if (!strcmp(s, "ucirc")) return 0xfb; /* û */
      if (!strcmp(s, "uuml")) return 0xfc; /* ü */
      return 0;
    case 'y':
      if (!strcmp(s, "yacute")) return 0xfd; /* ý */

  }
  return 0;
}

char *html_expand_amp_8859_1(const char *amp,
                                      char *buf)
{
  unsigned char ch;

  ch = _expand_amp_8859_1_char(amp);
  if (ch == '\0')
  {
    if (!strcmp(amp, "copy")) return "(C)";
    return "";
  }
  else {
    buf[0] = (char)ch;
    buf[1] = '\0';
    return buf;
  }
}

NEOERR *html_strip_alloc(const char *src, int slen,
                         char **out)
{
  NEOERR *err = STATUS_OK;
  STRING out_s;
  int x = 0;
  int strip_match = -1;
  int state = 0;
  char amp[10];
  int amp_start = 0;
  char buf[10];
  int ampl = 0;

  string_init(&out_s);
  err = string_append (&out_s, "");
  if (err) return nerr_pass (err);

  while (x < slen)
  {
    switch (state) {
      case 0:
	/* Default */
	if (src[x] == '&')
	{
	  state = 3;
	  ampl = 0;
	  amp_start = x;
	}
	else if (src[x] == '<')
	{
	  state = 1;
	}
	else
	{
	  if (strip_match == -1)
	  {
	    err = string_append_char(&out_s, src[x]);
	    if (err) break;
	  }
	}
	x++;
	break;
      case 1:
	/* Starting TAG */
	if (src[x] == '>')
	{
	  state = 0;
	}
	else if (src[x] == '/')
	{
	}
	else
	{
	}
	x++;
	break;
      case 2:
	/* In TAG */
	if (src[x] == '>')
	{
	  state = 0;
	}
	x++;
	break;
      case 3:
	/* In AMP */
	if (src[x] == ';')
	{
	  amp[ampl] = '\0';
	  state = 0;
	  err = string_append(&out_s, html_expand_amp_8859_1(amp, buf));
	  if (err) break;
	}
	else
	{
	  if (ampl < sizeof(amp)-1)
	    amp[ampl++] = tolower(src[x]);
	  else
	  {
	    /* broken html... just back up */
	    x = amp_start;
	    err = string_append_char(&out_s, src[x]);
	    if (err) break;
	    state = 0;
	  }
	}
	x++;
	break;
    }
    if (err) break;
  }


  if (err)
  {
    string_clear (&out_s);
    return nerr_pass (err);
  }
  *out = out_s.buf;
  return STATUS_OK;
}
clearsilver-0.10.5/cgi/html.h0000644001211700116100000000211310343717665012714 00000000000000/*
 * Copyright 2001-2004 Brandon Long
 * All Rights Reserved.
 *
 * ClearSilver Templating System
 *
 * This code is made available under the terms of the ClearSilver License.
 * http://www.clearsilver.net/license.hdf
 *
 */

#ifndef __HTML_H_ 
#define __HTML_H_ 1

#include 
#include "util/neo_err.h"
#include "util/neo_hdf.h"

__BEGIN_DECLS

typedef struct _text_html_opts {
    const char *bounce_url;
    const char *url_class;
    const char *url_target;
    const char *mailto_class;
    int long_lines;
    int space_convert;
    int newlines_convert;
    int longline_width;
    int check_ascii_art;
    const char *link_name;
} HTML_CONVERT_OPTS;

NEOERR *convert_text_html_alloc (const char *src, int slen, char **out);
NEOERR *convert_text_html_alloc_options (const char *src, int slen,
                                         char **out, 
                                         HTML_CONVERT_OPTS *opts);
NEOERR *html_escape_alloc (const char *src, int slen, char **out);
NEOERR *html_strip_alloc(const char *src, int slen, char **out);

__END_DECLS

#endif /* __HTML_H_ */
clearsilver-0.10.5/cgi/rfc2388.c0000644001211700116100000003244410474777202013052 00000000000000/*
 * Copyright 2001-2004 Brandon Long
 * All Rights Reserved.
 *
 * ClearSilver Templating System
 *
 * This code is made available under the terms of the ClearSilver License.
 * http://www.clearsilver.net/license.hdf
 *
 */

/* rfc2388 defines multipart/form-data which is primarily used for
 * HTTP file upload
 */

#include "cs_config.h"

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include "util/neo_misc.h"
#include "util/neo_err.h"
#include "util/neo_str.h"
#include "cgi.h"
#include "cgiwrap.h"

static NEOERR * _header_value (char *hdr, char **val)
{
  char *p, *q;
  int l;

  *val = NULL;

  p = hdr;
  while (*p && isspace(*p)) p++;
  q = p;
  while (*q && !isspace(*q) && *q != ';') q++;
  if (!*p || p == q) return STATUS_OK;

  l = q - p;
  *val = (char *) malloc (l+1);
  if (*val == NULL)
    return nerr_raise (NERR_NOMEM, "Unable to allocate space for val");
  memcpy (*val, p, l);
  (*val)[l] = '\0';

  return STATUS_OK;
}

static NEOERR * _header_attr (char *hdr, char *attr, char **val)
{
  char *p, *k, *v;
  int found = 0;
  int l, al;
  char *r;

  *val = NULL;
  l = strlen(attr);

  /* skip value */
  p = hdr;
  while (*p && *p != ';') p++;
  if (!*p) return STATUS_OK;

  p++;
  while(*p && !found)
  {
    while (*p && isspace(*p)) p++;
    if (!*p) return STATUS_OK;
    /* attr name */
    k = p;
    while (*p && !isspace(*p) && *p != ';' && *p != '=') p++;
    if (!*p) return STATUS_OK;
    if (l == (p-k) && !strncasecmp(attr, k, l))
      found = 1;

    while (*p && isspace(*p)) p++;
    if (*p != ';' && *p != '=') return STATUS_OK;
    if (*p == ';')
    {
      if (found)
      {
	*val = strdup ("");
	if (*val == NULL) 
	  return nerr_raise (NERR_NOMEM, "Unable to allocate value");
	return STATUS_OK;
      }
    }
    else 
    {
      p++;
      if (*p == '"')
      {
	v = ++p;
	while (*p && *p != '"') p++;
	al = p-v;
	if (*p) p++;
      }
      else
      {
	v = p;
	while (*p && !isspace(*p) && *p != ';') p++;
	al = p-v;
      }
      if (found)
      {
	r = (char *) malloc (al+1);
	if (r == NULL) 
	  return nerr_raise (NERR_NOMEM, "Unable to allocate value");
	memcpy (r, v, al);
	r[al] = '\0';
	*val = r;
	return STATUS_OK;
      }
    }
    if (*p) p++;
  }
  return STATUS_OK;
}

static NEOERR * _read_line (CGI *cgi, char **s, int *l, int *done)
{
  int ofs = 0;
  char *p;
  int to_read;

  if (cgi->buf == NULL)
  {
    cgi->buflen = 4096;
    cgi->buf = (char *) malloc (sizeof(char) * cgi->buflen);
    if (cgi->buf == NULL)
      return nerr_raise (NERR_NOMEM, "Unable to allocate cgi buf");
  }
  if (cgi->unget)
  {
    cgi->unget = FALSE;
    *s = cgi->last_start;
    *l = cgi->last_length;
    return STATUS_OK;
  }
  if (cgi->found_nl)
  {
    p = memchr (cgi->buf + cgi->nl, '\n', cgi->readlen - cgi->nl);
    if (p) {
      cgi->last_start = *s = cgi->buf + cgi->nl;
      cgi->last_length = *l = p - (cgi->buf + cgi->nl) + 1;
      cgi->found_nl = TRUE;
      cgi->nl = p - cgi->buf + 1;
      return STATUS_OK;
    }
    ofs = cgi->readlen - cgi->nl;
    memmove(cgi->buf, cgi->buf + cgi->nl, ofs);
  }
  // Read either as much buffer space as we have left, or up to 
  // the amount of data remaining according to Content-Length
  // If there is no Content-Length, just use the buffer space, but recognize
  // that it might not work on some servers or cgiwrap implementations.
  // Some servers will close their end of the stdin pipe, so cgiwrap_read
  // will return if we ask for too much.  Techically, not including
  // Content-Length is against the HTTP spec, so we should consider failing
  // earlier if we don't have a length.
  to_read = cgi->buflen - ofs;
  if (cgi->data_expected && (to_read > cgi->data_expected - cgi->data_read))
  {
    to_read = cgi->data_expected - cgi->data_read;
  }
  cgiwrap_read (cgi->buf + ofs, to_read, &(cgi->readlen));
  if (cgi->readlen < 0)
  {
    return nerr_raise_errno (NERR_IO, "POST Read Error");
  }
  if (cgi->readlen == 0)
  {
    *done = 1;
    return STATUS_OK;
  }
  cgi->data_read += cgi->readlen;
  if (cgi->upload_cb)
  {
    if (cgi->upload_cb (cgi, cgi->data_read, cgi->data_expected))
      return nerr_raise (CGIUploadCancelled, "Upload Cancelled");
  }
  cgi->readlen += ofs;
  p = memchr (cgi->buf, '\n', cgi->readlen);
  if (!p)
  {
    cgi->found_nl = FALSE;
    cgi->last_start = *s = cgi->buf;
    cgi->last_length = *l = cgi->readlen;
    return STATUS_OK;
  }
  cgi->last_start = *s = cgi->buf;
  cgi->last_length = *l = p - cgi->buf + 1;
  cgi->found_nl = TRUE;
  cgi->nl = *l;
  return STATUS_OK;
}

static NEOERR * _read_header_line (CGI *cgi, STRING *line, int *done)
{
  NEOERR *err;
  char *s, *p;
  int l;

  err = _read_line (cgi, &s, &l, done);
  if (err) return nerr_pass (err);
  if (*done || (l == 0)) return STATUS_OK;
  if (isspace (s[0])) return STATUS_OK;
  while (l && isspace(s[l-1])) l--;
  err = string_appendn (line, s, l);
  if (err) return nerr_pass (err);

  while (1)
  {
    err = _read_line (cgi, &s, &l, done);
    if (err) break;
    if (l == 0) break;
    if (*done) break;
    if (!(s[0] == ' ' || s[0] == '\t'))
    {
      cgi->unget = TRUE;
      break;
    }
    while (l && isspace(s[l-1])) l--;
    p = s;
    while (*p && isspace(*p) && (p-s < l)) p++;
    err = string_append_char (line, ' ');
    if (err) break;
    err = string_appendn (line, p, l - (p-s));
    if (err) break;
    if (line->len > 50*1024*1024)
    {
      string_clear(line);
      return nerr_raise(NERR_ASSERT, "read_header_line exceeded 50MB");
    }
  }
  return nerr_pass (err);
}

static BOOL _is_boundary (char *boundary, char *s, int l, int *done)
{
  static char *old_boundary = NULL;
  static int bl;

  /* cache the boundary strlen... more pointless optimization by blong */
  if (old_boundary != boundary)
  {
    old_boundary = boundary;
    bl = strlen(boundary);
  }

  if (s[l-1] != '\n')
    return FALSE;
  l--;
  if (s[l-1] == '\r')
    l--;

  if (bl+2 == l && s[0] == '-' && s[1] == '-' && !strncmp (s+2, boundary, bl))
    return TRUE;
  if (bl+4 == l && s[0] == '-' && s[1] == '-' && 
      !strncmp (s+2, boundary, bl) &&
      s[l-1] == '-' && s[l-2] == '-')
  {
    *done = 1;
    return TRUE;
  }
  return FALSE;
}

static NEOERR * _find_boundary (CGI *cgi, char *boundary, int *done)
{
  NEOERR *err;
  char *s;
  int l;

  *done = 0;
  while (1)
  {
    err = _read_line (cgi, &s, &l, done);
    if (err) return nerr_pass (err);
    if ((l == 0) || (*done)) {
      *done = 1;
      return STATUS_OK;
    }
    if (_is_boundary(boundary, s, l, done))
      return STATUS_OK;
  }
  return STATUS_OK;
}

NEOERR *open_upload(CGI *cgi, int unlink_files, FILE **fpw)
{
  NEOERR *err = STATUS_OK;
  FILE *fp;
  char path[_POSIX_PATH_MAX];
  int fd;

  *fpw = NULL;

  snprintf (path, sizeof(path), "%s/cgi_upload.XXXXXX", 
      hdf_get_value(cgi->hdf, "Config.Upload.TmpDir", "/var/tmp"));

  fd = mkstemp(path);
  if (fd == -1)
  {
    return nerr_raise_errno (NERR_SYSTEM, "Unable to open temp file %s", 
	path);
  }

  fp = fdopen (fd, "w+");
  if (fp == NULL)
  {
    close(fd);
    return nerr_raise_errno (NERR_SYSTEM, "Unable to fdopen file %s", path);
  }
  if (unlink_files) unlink(path);
  if (cgi->files == NULL)
  {
    err = uListInit (&(cgi->files), 10, 0);
    if (err)
    {
      fclose(fp);
      return nerr_pass(err);
    }
  }
  err = uListAppend (cgi->files, fp);
  if (err)
  {
    fclose (fp);
    return nerr_pass(err);
  }
  if (!unlink_files) {
    if (cgi->filenames == NULL)
    {
      err = uListInit (&(cgi->filenames), 10, 0);
      if (err)
      {
	fclose(fp);
	return nerr_pass(err);
      }
    }
    err = uListAppend (cgi->filenames, strdup(path));
    if (err)
    {
      fclose (fp);
      return nerr_pass(err);
    }
  }
  *fpw = fp;
  return STATUS_OK;
}

static NEOERR * _read_part (CGI *cgi, char *boundary, int *done)
{
  NEOERR *err = STATUS_OK;
  STRING str;
  HDF *child, *obj = NULL;
  FILE *fp = NULL;
  char buf[256];
  char *p;
  char *name = NULL, *filename = NULL;
  char *type = NULL, *tmp = NULL;
  char *last = NULL;
  int unlink_files = hdf_get_int_value(cgi->hdf, "Config.Upload.Unlink", 1);

  string_init (&str);

  while (1)
  {
    err = _read_header_line (cgi, &str, done);
    if (err) break;
    if (*done) break;
    if (str.buf == NULL || str.buf[0] == '\0') break;
    p = strchr (str.buf, ':');
    if (p)
    {
      *p = '\0';
      if (!strcasecmp(str.buf, "content-disposition"))
      {
	err = _header_attr (p+1, "name", &name);
	if (err) break;
	err = _header_attr (p+1, "filename", &filename);
	if (err) break;
      }
      else if (!strcasecmp(str.buf, "content-type"))
      {
	err = _header_value (p+1, &type);
	if (err) break;
      }
      else if (!strcasecmp(str.buf, "content-encoding"))
      {
	err = _header_value (p+1, &tmp);
	if (err) break;
	if (tmp && strcmp(tmp, "7bit") && strcmp(tmp, "8bit") && 
	    strcmp(tmp, "binary"))
	{
	  free(tmp);
	  err = nerr_raise (NERR_ASSERT, "form-data encoding is not supported");
	  break;
	}
	free(tmp);
      }
    }
    string_set(&str, "");
  }
  if (err) 
  {
    string_clear(&str);
    if (name) free(name);
    if (filename) free(filename);
    if (type) free(type);
    return nerr_pass (err);
  }

  do
  {
    if (filename)
    {
      err = open_upload(cgi, unlink_files, &fp);
      if (err) break;
    }

    string_set(&str, "");
    while (!(*done))
    {
      char *s;
      int l, w;

      err = _read_line (cgi, &s, &l, done);
      if (err) break;
      if (*done || (l == 0)) break;
      if (_is_boundary(boundary, s, l, done)) break;
      if (filename)
      {
	if (last) fwrite (last, sizeof(char), strlen(last), fp);
	if (l > 1 && s[l-1] == '\n' && s[l-2] == '\r')
	{
	  last = "\r\n";
	  l-=2;
	}
	else if (l > 0 && s[l-1] == '\n')
	{
	  last = "\n";
	  l--;
	}
	else last = NULL;
	w = fwrite (s, sizeof(char), l, fp);
	if (w != l)
	{
	  err = nerr_raise_errno (NERR_IO, 
	      "Short write on file %s upload %d < %d", filename, w, l);
	  break;
	}
      }
      else
      {
	err = string_appendn(&str, s, l);
	if (err) break;
      }
    }
    if (err) break;
  } while (0);

  /* Set up the cgi data */
  if (!err)
  {
    do {
      /* FIXME: Hmm, if we've seen the same name here before, what should we do?
       */
      if (filename)
      {
	fseek(fp, 0, SEEK_SET);
	snprintf (buf, sizeof(buf), "Query.%s", name);
	err = hdf_set_value (cgi->hdf, buf, filename);
	if (!err && type)
	{
	  snprintf (buf, sizeof(buf), "Query.%s.Type", name);
	  err = hdf_set_value (cgi->hdf, buf, type);
	}
	if (!err)
	{
	  snprintf (buf, sizeof(buf), "Query.%s.FileHandle", name);
	  err = hdf_set_int_value (cgi->hdf, buf, uListLength(cgi->files));
	}
	if (!err && !unlink_files)
	{
	  char *path;
	  snprintf (buf, sizeof(buf), "Query.%s.FileName", name);
	  err = uListGet(cgi->filenames, uListLength(cgi->filenames)-1, 
	      (void *)&path);
	  if (!err) err = hdf_set_value (cgi->hdf, buf, path);
	}
      }
      else
      {
	snprintf (buf, sizeof(buf), "Query.%s", name);
	while (str.len && isspace(str.buf[str.len-1]))
	{
	  str.buf[str.len-1] = '\0';
	  str.len--;
	}
	if (!(cgi->ignore_empty_form_vars && str.len == 0))
	{
	  /* If we've seen it before... we force it into a list */
	  obj = hdf_get_obj (cgi->hdf, buf);
	  if (obj != NULL)
	  {
	    int i = 0;
	    char buf2[10];
	    char *t;
	    child = hdf_obj_child (obj);
	    if (child == NULL)
	    {
	      t = hdf_obj_value (obj);
	      err = hdf_set_value (obj, "0", t);
	      if (err != STATUS_OK) break;
	      i = 1;
	    }
	    else
	    {
	      while (child != NULL)
	      {
		i++;
		child = hdf_obj_next (child);
		if (err != STATUS_OK) break;
	      }
	      if (err != STATUS_OK) break;
	    }
	    snprintf (buf2, sizeof(buf2), "%d", i);
	    err = hdf_set_value (obj, buf2, str.buf);
	    if (err != STATUS_OK) break;
	  }
	  err = hdf_set_value (cgi->hdf, buf, str.buf);
	}
      }
    } while (0);
  }

  string_clear(&str);
  if (name) free(name);
  if (filename) free(filename);
  if (type) free(type);

  return nerr_pass (err);
}

NEOERR * parse_rfc2388 (CGI *cgi)
{
  NEOERR *err;
  char *ct_hdr;
  char *boundary = NULL;
  int l;
  int done = 0;

  l = hdf_get_int_value (cgi->hdf, "CGI.ContentLength", -1);
  ct_hdr = hdf_get_value (cgi->hdf, "CGI.ContentType", NULL);
  if (ct_hdr == NULL) 
    return nerr_raise (NERR_ASSERT, "No content type header?");

  cgi->data_expected = l;
  cgi->data_read = 0;
  if (cgi->upload_cb)
  {
    if (cgi->upload_cb (cgi, cgi->data_read, cgi->data_expected))
      return nerr_raise (CGIUploadCancelled, "Upload Cancelled");
  }

  err = _header_attr (ct_hdr, "boundary", &boundary);
  if (err) return nerr_pass (err);
  err = _find_boundary(cgi, boundary, &done);
  while (!err && !done)
  {
    err = _read_part (cgi, boundary, &done);
  }

  if (boundary) free(boundary);
  return nerr_pass(err);
}

/* this is here because it gets populated in this file */
FILE *cgi_filehandle (CGI *cgi, const char *form_name)
{
  NEOERR *err;
  FILE *fp;
  char buf[256];
  int n;

  if ((form_name == NULL) || (form_name[0] == '\0'))
  {
    /* if NULL, then its the PUT data we're looking for... */
    n = hdf_get_int_value (cgi->hdf, "PUT.FileHandle", -1);
  }
  else
  {
    snprintf (buf, sizeof(buf), "Query.%s.FileHandle", form_name);
    n = hdf_get_int_value (cgi->hdf, buf, -1);
  }
  if (n == -1) return NULL;
  err = uListGet(cgi->files, n-1, (void *)&fp);
  if (err)
  {
    nerr_ignore(&err);
    return NULL;
  }
  return fp;
}
clearsilver-0.10.5/cgi/static.c0000644001211700116100000000773610325273357013245 00000000000000/*
 * Copyright 2001-2004 Brandon Long
 * All Rights Reserved.
 *
 * ClearSilver Templating System
 *
 * This code is made available under the terms of the ClearSilver License.
 * http://www.clearsilver.net/license.hdf
 *
 */

/* static.cgi
 * This is a really simple example of how you can map URL requests to a set of
 * hdf and cs files.
 */

#include "ClearSilver.h"

#include 
#include 
#include 
#include 
#include 

int main(int argc, char **argv, char **envp)
{
  NEOERR *err;
  CGI *cgi;
  char *cs_file;
  char hdf_file[_POSIX_PATH_MAX];
  char *p;

  /* CGI works by passing information from the server to the CGI program via
   * environment variables and stdin.  cgi_debug_init looks for a file as the
   * first argument, and loads it.  That file contains key=value pairs which
   * cgi_debug_init will load into the environment, allowing you to test your
   * program via the command line. */
  cgi_debug_init(argc, argv);

  /* The ClearSilver cgi toolkit accesses the CGI environment through a
   * wrapper.  This allows the program to be used in other environments and
   * fake the CGI environment, such as FastCGI, mod_python, PyApache, or even
   * just from Python to access the python objects instead of the libc API.
   * cgiwrap_init_std just sets up for the default CGI environment using the
   * libc api. */
  cgiwrap_init_std(argc, argv, envp);

  /* cgi_init creates a CGI struct, and parses the CGI environment variables. 
   * It creates an HDF structure as well.  */
  err = cgi_init(&cgi, NULL);
  if (err != STATUS_OK)
  {
    /* cgi_neo_error renders a NEOERR as an error CGI result */
    cgi_neo_error(cgi, err);
    /* nerr_log_error logs the error to stderr and cleans up */
    nerr_log_error(err);
    return -1;
  }

  /* CGI.PathTranslated is a CGI env var which maps the URL with the
   * DocumentRoot to give you the location of the referenced file on disk */
  cs_file = hdf_get_value(cgi->hdf, "CGI.PathTranslated", NULL);
  if (cs_file == NULL)
  {
    /* cgi_error returns a simple error page */
    cgi_error(cgi, "No PATH_TRANSLATED var");
    return -1;
  }

  /* The hdf.loadpaths variables specify where HDF and ClearSilver look for
   * files on the file system.  We start setting that up here based on
   * the directory of the file referenced */
  p = strrchr (cs_file, '/');
  if (p)
  {
    *p = '\0';
    err = hdf_set_value(cgi->hdf, "hdf.loadpaths.0", cs_file);
    chdir(cs_file);
    *p = '/';
    if (err)
    {
      cgi_neo_error(cgi, err);
      nerr_log_error(err);
      return -1;
    }
  }
  /* Next, we look for a shared HDF static dataset in common.hdf */
  err = hdf_read_file(cgi->hdf, "common.hdf");
  if (err && !nerr_handle(&err, NERR_NOT_FOUND))
  {
    cgi_neo_error(cgi, err);
    nerr_log_error(err);
    return -1;
  }
  /* Next, we look for an HDF file for this specific page.  We first look
   * for passedfile.html.hdf, then we check for a file by removing an extension
   * from the file, so something like passedfile.html we'll look for
   * passedfile.hdf */
  snprintf (hdf_file, sizeof(hdf_file), "%s.hdf", cs_file);
  err = hdf_read_file (cgi->hdf, hdf_file);
  if (err && !nerr_handle(&err, NERR_NOT_FOUND))
  {
    cgi_neo_error(cgi, err);
    nerr_log_error(err);
    return -1;
  }
  p = strrchr (cs_file, '.');
  if (p)
  {
    *p = '\0';
    snprintf (hdf_file, sizeof(hdf_file), "%s.hdf", cs_file);
    *p = '.';
    err = hdf_read_file (cgi->hdf, hdf_file);
    if (err && !nerr_handle(&err, NERR_NOT_FOUND))
    {
      cgi_neo_error(cgi, err);
      nerr_log_error(err);
      return -1;
    }
  }
  /* Lastly, we need to render a template.  The template is either the
   * file that was passed to us, or its specificed by CGI.StaticContent
   * in one of the HDF files we loaded above. */
  cs_file = hdf_get_value (cgi->hdf, "CGI.StaticContent", cs_file);
  err = cgi_display (cgi, cs_file);
  if (err != STATUS_OK)
  {
    cgi_neo_error(cgi, err);
    nerr_log_error(err);
    return -1;
  }
  return 0;
}
clearsilver-0.10.5/python/0000755001211700116100000000000010645505045012431 500000000000000clearsilver-0.10.5/python/Makefile0000644001211700116100000000215510455366605014022 00000000000000

ifeq ($(NEOTONIC_ROOT),)
NEOTONIC_ROOT = ..
endif

include $(NEOTONIC_ROOT)/rules.mk

NEO_UTIL_SO = neo_cgi.so
NEO_UTIL_PYD = neo_cgi.pyd
NEO_UTIL_SRC = neo_cgi.c neo_util.c neo_cs.c
NEO_UTIL_OBJ = $(NEO_UTIL_SRC:%.c=%.o)

CFLAGS += $(PYTHON_INC)
DLIBS += -lneo_cgi -lneo_cs -lneo_utl 
LIBS += $(DLIBS) $(DB2_LIB)

ifeq ($(USE_MINGW32),1)
TARGETS = $(NEO_UTIL_PYD)
else
TARGETS = $(NEO_UTIL_SO)
endif

all: $(TARGETS)

$(NEO_UTIL_SO): setup.py $(NEO_UTIL_SRC) $(DEP_LIBS)
	rm -f $(NEO_UTIL_SO)
	CC="$(CC)" LDSHARED="$(LDSHARED)" $(PYTHON) setup.py build_ext --inplace

OLD_NEO_UTIL_SO:
	$(LDSHARED) -o $@ $(LDFLAGS) $(NEO_UTIL_OBJ) $(LIBS)

setup:
	$(PYTHON) setup.py build_ext --inplace

$(NEO_UTIL_PYD): $(NEO_UTIL_OBJ) $(DEP_LIBS)
	dllwrap --dllname neo_cgi.pyd --driver-name gcc \
		--def neo_cgi.def -o neo_cgi.pyd \
		$(NEO_UTIL_OBJ) -s --entry _DllMain@12 \
		--target=i386-mingw32 \
		$(LDFLAGS) $(PYTHON_LIB) $(LIBS)

install: all
	$(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(PYTHON_SITE)
	$(INSTALL) $(TARGETS) $(DESTDIR)$(PYTHON_SITE)

clean:
	$(RM) *.o

distclean:
	$(RM) Makefile.depends $(TARGETS) *.o
	$(RM) -r build
clearsilver-0.10.5/python/README.txt0000644001211700116100000000546710261037513014055 00000000000000------------------------
Python Clearsilver Module
By Brandon Long

Windows port by David Jeske
------------------------

This is the python clearsilver module. You can see the online
documentation for the Python API here:

  http://www.clearsilver.net/docs/python/

COMPILING on UNIX

Compiling from source on Linux (UNIX) should be pretty
straightforward. Simply make sure that the Makefile and top level
rules.mk point to your Python installation of choice. Comments or
questions to blong@fiction.net

WINDOWS BINARY

If you are using Python2.2, we highly recommend you download the
pre-built binary. You can download a windows binary of the module from
the clearsilver download page here:

  http://www.clearsilver.net/downloads/

COMPILING on Windows

If you must compile on windows, here is the set of steps you need to
follow for Python22. Comments or questions to jeske@chat.net.

1) Download and Install Python2.2 from:

   http://www.python.org/ftp/python/2.2.1/Python-2.2.1.exe

2) Download and Install Mingw32-2.0 and binutils from:

   http://prdownloads.sourceforge.net/mingw/MinGW-2.0.0-3.exe?download
   http://prdownloads.sourceforge.net/mingw/binutils-2.13-20020903-1.tar.gz?download

3) Download and Install UNIX Tools and Make from:

   http://unxutils.sourceforge.net/UnxUtils.zip

   http://prdownloads.sourceforge.net/mingw/make-3.79.1-20010722.tar.gz 

**** ALTERNATIVELY *****
  
    You can use msys, just download 1.08 or later (well, that's what I
    tested) at:
    http://prdownloads.sourceforge.net/mingw/MSYS-1.0.8.exe

4) Add the mingw32 binary directory to your path

**** ALTERNATIVELY *****
  
    Using msys, just click on the msys icon on your desktop to launch
    the sh command line window.  Note that the python executable won't
    do screen output correctly from this window, but it does work.

5) Build the libpython22.a import library using these steps:

   a) Download the Py-mingw32 tools:

     http://starship.python.net/crew/kernr/mingw32/Py-mingw32-tools.zip

   b) extract them to C:\Python22\libs

   c) edit lib2def.py and replace python15->python22, Python15->Python22

   d) execute these commands:

       C:\Python22\libs> lib2def.py python22.lib > python22.def
       C:\Python22\libs> dlltool --dllname python22.dll --def python22.def --output-lib libpython22.a

   Reference:

   http://starship.python.net/pipermail/mmtk/2002/000398.html

6) Check the python library and include paths in the neotonic/rules.mk

  You should see:
    PYTHON_INC = -I/c/python22/include
    PYTHON_LIB = -L/c/python22/libs -lpython22
  
  These should have been found automatically by the configure script.

7) Then type "make" in the neotonic\python directory... 
  
  Ignore all the warnings aboue HAVE_ defines being re-defined.  This
  are just collisions between the clearsilver config file and the python
  config file.
clearsilver-0.10.5/python/examples/0000755001211700116100000000000010645505045014247 500000000000000clearsilver-0.10.5/python/examples/base/0000755001211700116100000000000010645505044015160 500000000000000clearsilver-0.10.5/python/examples/base/CSPage.py0000755001211700116100000001627710261037513016567 00000000000000#!/neo/opt/bin/python

import neo_cgi
import sys, os, string
import time
from log import *

# errors thrown...
NoPageName = "NoPageName"
NoDisplayMethod = "NoDisplayMethod"

# errors signaled back to here
Redirected = "Redirected"
DisplayDone = "DisplayDone"
DisplayError = "DisplayError"

class Context:
    def __init__ (self):
        self.argv = sys.argv
        self.stdin = sys.stdin
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        self.environ = os.environ

class CSPage:
    def __init__(self, context, pagename=0,readDefaultHDF=1,israwpage=0,**parms):
        if pagename == 0:
            raise NoPageName, "missing pagename"
        self.pagename = pagename
        self.readDefaultHDF = readDefaultHDF
        self._israwpage = israwpage
        self.context = context
        self._pageparms = parms

        self._error_template = None

        self.page_start_time = time.time()
        neo_cgi.cgiWrap(context.stdin, context.stdout, context.environ)
        neo_cgi.IgnoreEmptyFormVars(1)
        self.ncgi = neo_cgi.CGI()
        self.ncgi.parse()
        self._path_num = 0
        domain = self.ncgi.hdf.getValue("CGI.ServerName","")
        domain = self.ncgi.hdf.getValue("HTTP.Host", domain)
        self.domain = domain
        self.subclassinit()
        self.setPaths([self.ncgi.hdf.getValue("CGI.DocumentRoot","")])

    def subclassinit(self):
        pass

    def setPaths(self, paths):
        for path in paths:  
            self.ncgi.hdf.setValue("hdf.loadpaths.%d" % self._path_num, path)
            self._path_num = self._path_num + 1
            
    def redirectUri(self,redirectTo):
        ncgi = self.ncgi
        if ncgi.hdf.getIntValue("Cookie.debug",0) == 1:
            ncgi.hdf.setValue("CGI.REDIRECT_TO",redirectTo)
            ncgi.display("dbg/redirect.cs")
            print "
"
            print neo_cgi.htmlEscape(ncgi.hdf.dump())
            print "
" raise DisplayDone self.ncgi.redirectUri(redirectTo) raise Redirected, "redirected To: %s" % redirectTo ## ---------------------------------- ## methods to be overridden in subclass when necessary: def setup(self): pass def display(self): raise NoDisplayMethod, "no display method present in %s" % repr(self) def main(self): self.setup() self.handle_actions() self.display() ## ---------------------------------- def handle_actions(self): hdf = self.ncgi.hdf hdfobj = hdf.getObj("Query.Action") if hdfobj: firstchild = hdfobj.child() if firstchild: action = firstchild.name() if firstchild.next(): raise "multiple actions present!!!" method_name = "Action_%s" % action method = getattr(self,method_name) apply(method,[]) def start(self): SHOULD_DISPLAY = 1 if self._israwpage: SHOULD_DISPLAY = 0 ncgi = self.ncgi if self.readDefaultHDF: try: if not self.pagename is None: ncgi.hdf.readFile("%s.hdf" % self.pagename) except: log("Error reading HDF file: %s.hdf" % (self.pagename)) DISPLAY_ERROR = 0 ERROR_MESSAGE = "" # call page main function! try: self.main() except DisplayDone: SHOULD_DISPLAY = 0 except Redirected: # catch redirect exceptions SHOULD_DISPLAY = 0 except DisplayError, num: ncgi.hdf.setValue("Query.error", str(num)) if self._error_template: ncgi.hdf.setValue("Content", self._error_template) else: DISPLAY_ERROR = 1 except: SHOULD_DISPLAY = 0 DISPLAY_ERROR = 1 import handle_error handle_error.handleException("Display Failed!") ERROR_MESSAGE = handle_error.exceptionString() if DISPLAY_ERROR: print "Content-Type: text/html\n\n" # print the page print "

Error in Page

" print "A copy of this error report has been submitted to the developers. " print "The details of the error report are below." print "
"
            print neo_cgi.htmlEscape(ERROR_MESSAGE)
            print "
\n" # print debug info always on page error... print "
\n" print "
"
            print neo_cgi.htmlEscape(ncgi.hdf.dump())
            print "
" etime = time.time() - self.page_start_time ncgi.hdf.setValue("CGI.debug.execute_time","%f" % (etime)) if SHOULD_DISPLAY and self.pagename: debug_output = ncgi.hdf.getIntValue("page.debug",ncgi.hdf.getIntValue("Cookie.debug",0)) # hijack the built-in debug output method... if ncgi.hdf.getValue("Query.debug","") == ncgi.hdf.getValue("Config.DebugPassword","1"): ncgi.hdf.setValue("Config.DebugPassword","CSPage.py DEBUG hijack (%s)" % ncgi.hdf.getValue("Config.DebugPassword","")) debug_output = 1 if not debug_output: ncgi.hdf.setValue("Config.CompressionEnabled","1") # default display template_name = ncgi.hdf.getValue("Content","%s.cs" % self.pagename) # ncgi.hdf.setValue ("cgiout.charset", "utf-8"); try: ncgi.display(template_name) except: print "Content-Type: text/html\n\n" print "CSPage: Error occured" import handle_error print "
" + handle_error.exceptionString() + "
" debug_output = 1 # debug output if debug_output: print "
\n" print "CSPage Debug, Execution Time: %5.3f

" % (etime) print "
"
                print neo_cgi.htmlEscape(ncgi.hdf.dump())
                print "
" # ncgi.hdf.setValue("hdf.DEBUG",ncgi.hdf.dump()) # ncgi.display("debug.cs") script_name = ncgi.hdf.getValue("CGI.ScriptName","") if script_name: script_name = string.split(script_name,"/")[-1] log ("[%s] etime/dtime: %5.3f/%5.3f %s (%s)" % (self.domain, etime, time.time() - etime - self.page_start_time, script_name, self.pagename)) # a protected output function to catch the output errors that occur when # the server is either restarted or the user pushes the stop button on the # browser def output(self, str): try: self.context.stdout.write(str) except IOError, reason: log("IOError: %s" % (repr(reason))) raise DisplayDone def allQuery (self, s): l = [] if self.ncgi.hdf.getValue ("Query.%s.0" % s, ""): obj = self.ncgi.hdf.getChild ("Query.%s" % s) while obj: l.append(obj.value()) obj = obj.next() else: t = self.ncgi.hdf.getValue ("Query.%s" % s, "") if t: l.append(t) return l clearsilver-0.10.5/python/examples/base/PassSGMLParser.py0000755001211700116100000000304010261037513020213 00000000000000## ## deja-vu batman, didn't I write this before? ## This parser is designed to parse an SGML document, and the default action ## is just to pass the data through. Based on TestSGMLParser from sgmllib.py ## Hmm, actually, make it a flag whether to handle unknown elements ## from sgmllib import SGMLParser class PassSGMLParser(SGMLParser): def __init__(self, fp, pass_unknown=0, verbose=0): self.pass_unknown = pass_unknown self.data = "" self.fp = fp SGMLParser.__init__(self, verbose) def handle_data(self, data): self.data = self.data + data def flush(self): data = self.data if data: self.data = "" self.write(data) def write (self, data): return self.fp.write(data) def write_starttag (self, tag, attrs): self.flush() if not attrs: self.write ("<%s>" % tag) else: self.write ("<" + tag) for name, value in attrs: self.write (" " + name + '=' + '"' + value + '"') self.write (">") def write_endtag (self, tag): self.flush() self.write ("" % tag) def handle_comment(self, data): # don't pass comments pass def unknown_starttag(self, tag, attrs): if self.pass_unknown: self.write_starttag (tag, attrs) def unknown_endtag(self, tag): if self.pass_unknown: self.write_endtag(tag) def handle_entityref(self, ref): self.flush() self.write ("&%s;" % ref) def handle_charref(self, ref): self.flush() self.write ("&#%s;" % ref) def close(self): SGMLParser.close(self) self.flush() clearsilver-0.10.5/python/examples/base/SafeHtml.py0000755001211700116100000001247210332515222017156 00000000000000## another case of deja-vu ## this time, we want the slashdot style (what Yahoo said to do) only allow ## certain tags... we'll make it an option ## we'll have to tie this in some way to our HTML body displayer... ## ## Ok, there are basically four types of tags: ## 1) safe - ie, , , etc. ## 2) render problems - - these we either strip, ## or we have to ensure they match ## 3) definitely evil independent tags that we always strip ## 4) definitely evil tags which denote a region, we strip the entire region from PassSGMLParser import PassSGMLParser from urllib import basejoin import string, sys import neo_cgi try: from cStringIO import StringIO except: from StringIO import StringIO class SafeHtml (PassSGMLParser): _safeTags = {"P":1, "LI":1, "DD":1, "DT":1, "EM":1, "BR":1, "CITE":1, "DFN":1, "Q":1, "STRONG":1, "IMG":1, "HR":1, "TR":1, "TD":1, "TH":1, "CAPTION":1, "THEAD":1, "TFOOT":1, "TBODY":1} _matchTags = {"TABLE":1, "OL":1, "UL":1, "DL":1, "CENTER":1, "DIV":1, "PRE":1, "SUB":1, "SUP":1, "BIG":1, "SMALL":1, "CODE":1, "B":1, "I":1, "A":1, "TT":1, "BLOCKQUOTE":1, "U":1, "H1":1, "H2":1, "H3":1, "H4":1, "H5":1, "H6":1, "FONT":1} _skipTags = {"FORM":1, "HTML":1, "BODY":1, "EMBED":1, "AREA":1, "MAP":1, "FRAME":1, "FRAMESET":1, "IFRAME":1, "META":1} _stripTags = {"HEAD":1, "JAVA":1, "APPLET":1, "OBJECT":1, "JAVASCRIPT":1, "LAYER":1, "STYLE":1, "SCRIPT":1} def __init__ (self, fp, extra_safe=1, base=None, map_urls=None, new_window=1): self._extra_safe = extra_safe PassSGMLParser.__init__ (self, fp, extra_safe) self._matchDict = {} self._stripping = 0 self._base = base self._map_urls = map_urls self._new_window = new_window def safe_start_strip (self): if self._stripping == 0: self.flush() self._stripping = self._stripping + 1 def safe_end_strip (self): self.flush() self._stripping = self._stripping - 1 if self._stripping < 0: self._stripping = 0 def write (self, data): # sys.stderr.write("write[%d] %s\n" % (self._stripping, data)) if self._stripping == 0: # sys.stderr.write("write %s\n" % data) PassSGMLParser.write(self, data) def cleanup_attrs (self, tag, attrs): new_attrs = [] tag = string.lower(tag) if self._new_window and tag == "a": new_attrs.append(('target', '_blank')) for name, value in attrs: name = string.lower(name) if name[:2] == "on": continue ## skip any javascript events if string.lower(value)[:11] == "javascript:": continue if self._map_urls and name in ["action", "href", "src", "lowsrc", "background"] and value[:4] == 'cid:': try: value = self._map_urls[value[4:]] except KeyError: pass else: if self._base and name in ["action", "href", "src", "lowsrc", "background"]: value = basejoin (self._base, value) if name in ["action", "href", "src", "lowsrc", "background"]: value = 'http://www.google.com/url?sa=D&q=%s' % (neo_cgi.urlEscape(value)) if self._new_window and tag == "a" and name == "target": continue new_attrs.append ((name, value)) return new_attrs def unknown_starttag(self, tag, attrs): tag = string.upper(tag) if SafeHtml._stripTags.has_key(tag): self.safe_start_strip() # sys.stderr.write("Stripping tag %s: %d\n" % (tag, self._stripping)) elif SafeHtml._skipTags.has_key(tag): # sys.stderr.write("Skipping tag %s\n" % tag) pass elif SafeHtml._matchTags.has_key(tag): # sys.stderr.write("Matching tag %s\n" % tag) if self._matchDict.has_key(tag): self._matchDict[tag] = self._matchDict[tag] + 1 else: self._matchDict[tag] = 1 self.write_starttag (tag, self.cleanup_attrs(tag, attrs)) elif SafeHtml._safeTags.has_key(tag): # sys.stderr.write("Safe tag %s\n" % tag) self.write_starttag (tag, self.cleanup_attrs(tag, attrs)) elif not self._extra_safe: # sys.stderr.write("Other tag %s\n" % tag) self.write_starttag (tag, self.cleanup_attrs(tag, attrs)) def unknown_endtag(self, tag): tag = string.upper(tag) if SafeHtml._stripTags.has_key(tag): self.safe_end_strip() # sys.stderr.write("End Stripping tag %s: %d\n" % (tag, self._stripping)) elif self._stripping == 0: if SafeHtml._skipTags.has_key(tag): pass elif SafeHtml._matchTags.has_key(tag): if self._matchDict.has_key(tag): self._matchDict[tag] = self._matchDict[tag] - 1 self.write_endtag (tag) elif SafeHtml._safeTags.has_key(tag): self.write_endtag (tag) elif not self._extra_safe: self.write_endtag (tag) def close (self): self._stripping = 0 for tag in self._matchDict.keys(): if self._matchDict[tag] > 0: for x in range (self._matchDict[tag]): self.write_endtag(tag) PassSGMLParser.close(self) def SafeHtmlString (s, really_safe=1, map_urls=None): # fp = open("/tmp/safe_html.in", "w") # fp.write(s) # fp.close() fp = StringIO() parser = SafeHtml(fp, really_safe, map_urls=map_urls) parser.feed (s) parser.close () s = fp.getvalue() # fp = open("/tmp/safe_html.out", "w") # fp.write(s) # fp.close() return s clearsilver-0.10.5/python/examples/base/__init__.py0000755001211700116100000000000010261037513017175 00000000000000clearsilver-0.10.5/python/examples/base/handle_error.py0000755001211700116100000000503210261037513020114 00000000000000 import traceback, sys, string, time, socket, os import who_calls #DUMP_DIR = "/neo/data/bugs" DUMP_DIR = "/tmp/bugs" Warning = "handle_error.Warning" # levels LV_MESSAGE = "LV_MESSAGE" LV_WARNING = "LV_WARNING" LV_ERROR = "LV_ERROR" Count = 0 gErrorCount = 0 DISABLE_DUMP = 0 def exceptionReason(): return "%s.%s" % (str(sys.exc_type), str(sys.exc_value)) def exceptionString(): tb_list = traceback.format_exception(sys.exc_type,sys.exc_value,sys.exc_traceback) return string.join(tb_list,"") #### old way import StringIO ## get the traceback message sfp = StringIO.StringIO() traceback.print_exc(file=sfp) exception = sfp.getvalue() sfp.close() return exception def handleException (msg=None, lvl=LV_ERROR, dump = 1): global gErrorCount gErrorCount = gErrorCount + 1 tb_list = traceback.format_exception(sys.exc_type,sys.exc_value,sys.exc_traceback) if msg: sys.stderr.write ("%s\n" % msg) else: msg = "Unhandled Exception" sys.stderr.write (string.join(tb_list,"")) try: if dump: dump_bug(lvl, "handleException", msg, string.join(tb_list, "")) except: handleException("Unable to dump_bug", dump = 0) def handleWarning (msg=""): header = "*** handleWarning: %s\n" % msg sys.stderr.write(header) tb = who_calls.pretty_who_calls(strip=1) + "\n" sys.stderr.write(tb) try: dump_bug(LV_WARNING, "handleException", msg, tb) except: handleException("Unable to dump_bug", dump = 0) def checkPaths(): paths = (DUMP_DIR, os.path.join (DUMP_DIR, "tmp"), os.path.join (DUMP_DIR, "new")) for path in paths: if not os.path.isdir(path): os.mkdir(path, 0755) def dump_bug (level, etype, msg, location=None, nhdf=None): global DISABLE_DUMP if DISABLE_DUMP: return now = int(time.time()) pid = os.getpid() import neo_cgi, neo_util hdf = neo_util.HDF() hdf.setValue("Required.Level", level) hdf.setValue("Required.When", str(int(time.time()))) hdf.setValue("Required.Type", etype) hdf.setValue("Required.Title", msg) hdf.setValue("Optional.Hostname", socket.gethostname()) if location: hdf.setValue("Optional.Location", location) for (key, value) in os.environ.items(): hdf.setValue ("Environ.%s" % key, value) global Count Count = Count + 1 fname = "%d.%d_%d.%s" % (now, pid, Count, socket.gethostname()) checkPaths() tpath = os.path.join (DUMP_DIR, "tmp", fname) npath = os.path.join (DUMP_DIR, "new", fname) hdf.writeFile(tpath) os.rename(tpath, npath) clearsilver-0.10.5/python/examples/base/hdfhelp.py0000755001211700116100000001515710261037513017073 00000000000000#!/neo/opt/bin/python # # Copyright (C) 2001 by Neotonic Software Corporation # All Rights Reserved. # # hdfhelp.py # # This code makes using odb with Clearsilver as "easy as stealing candy # from a baby". - jeske # # How to use: # # rows = tbl.fetchAllRows() # rows.hdfExport("CGI.rows", hdf_dataset) # # row = tbl.fetchRow( ('primary_key', value) ) # row.hdfExport("CGI.row", hdf_dataset) # # How to setup: # # # define table # class AgentsTable(odb.Table): # def _defineRows(self): # self.d_addColumn("agent_id",kInteger,None,primarykey = 1,autoincrement = 1) # self.d_addColumn("login",kVarString,200,notnull=1) # self.d_addColumn("ticket_count",kIncInteger,None) # # # make sure you return a subclass of hdfhelp.HdfRow # # def defaultRowClass(self): # return hdfhelp.HdfRow # def defaultRowListClass(self): # return hdfhelp.HdfItemList # import string, os import neo_cgi import neo_cs import neo_util import odb import time import UserList SECS_IN_MIN = 60 SECS_IN_HOUR = (SECS_IN_MIN * 60) SECS_IN_DAY = (SECS_IN_HOUR * 24) SECS_IN_WEEK = (SECS_IN_DAY * 7) SECS_IN_MONTH = (SECS_IN_DAY * 30) kYearPos = 0 kMonthPos = 1 kDayPos = 2 kHourPos = 3 kMinutePos = 4 kSecondPos = 5 kWeekdayPos = 6 kJulianDayPos = 7 kDSTPos = 8 def renderDate(then_time,day=0): if then_time is None: then_time = 0 then_time = int(then_time) if then_time == 0 or then_time == -1: return "" then_tuple = time.localtime(then_time) now_tuple = time.localtime(time.time()) if day or (then_tuple[kHourPos]==0 and then_tuple[kMinutePos]==0 and then_tuple[kSecondPos]==0): # it's just a date if then_tuple[kYearPos] == now_tuple[kYearPos]: # no year return time.strftime("%m/%d",then_tuple) else: # add year return time.strftime("%m/%d/%Y",then_tuple) else: # it's a full time/date return time.strftime("%m/%d/%Y %I:%M%p",then_tuple) class HdfRow(odb.Row): def hdfExport(self, prefix, hdf_dataset, *extra, **extranamed): skip_fields = extranamed.get("skip_fields", None) translate_dict = extranamed.get("translate_dict", None) tz = extranamed.get("tz", "US/Pacific") for col_name,value in self.items(): if skip_fields and (col_name in skip_fields): continue try: name,col_type,col_options = self._table.getColumnDef(col_name) except: col_type = odb.kVarString col_options = {} if (value is not None): if col_options.get("no_export",0): continue if type(value) in [ type(0), type(0L) ]: hdf_dataset.setValue(prefix + "." + col_name,"%d" % value) elif type(value) == type(1.0): if int(value) == value: hdf_dataset.setValue(prefix + "." + col_name,"%d" % value) else: hdf_dataset.setValue(prefix + "." + col_name,"%0.2f" % value) else: if col_type == odb.kReal: log("why are we here with this value: %s" % value) if translate_dict: for k,v in translate_dict.items(): value = string.replace(value,k,v) hdf_dataset.setValue(prefix + "." + col_name,neo_cgi.htmlEscape(str(value))) if col_options.get("int_date",0): hdf_dataset.setValue(prefix + "." + col_name + ".string",renderDate(value)) hdf_dataset.setValue(prefix + "." + col_name + ".day_string",renderDate(value,day=1)) if value: neo_cgi.exportDate(hdf_dataset, "%s.%s" % (prefix, col_name), tz, value) if col_options.has_key("enum_values"): enum = col_options["enum_values"] hdf_dataset.setValue(prefix + "." + col_name + ".enum", str(enum.get(value,''))) class HdfItemList(UserList.UserList): def hdfExport(self,prefix,hdf_dataset,*extra,**extranamed): export_by = extranamed.get("export_by", None) n = 0 for row in self: if export_by is not None: n = row[export_by] row.hdfExport("%s.%d" % (prefix,n),hdf_dataset,*extra,**extranamed) n = n + 1 def setList(hdf, prefix, lst): hdf.setValue(prefix+".0", str(len(lst))) for n in range(len(lst)): hdf.setValue(prefix+".%d" %(n+1), lst[n]); def getList(hdf, name): lst = [] for n in range(hdf.getIntValue(name,0)): lst.append(hdf.getValue(name+".%d" %(n+1), "")) return lst def eval_cs(hdf,a_cs_string): cs = neo_cs.CS(hdf) try: cs.parseStr(a_cs_string) return cs.render() except: return "Error in CS tags: %s" % neo_cgi.htmlEscape(repr(a_cs_string)) def childloop(hdf): children = [] if hdf: hdf = hdf.child() while hdf: children.append(hdf) hdf = hdf.next() return children # ---------------------------- class HDF_Database(odb.Database): def defaultRowClass(self): return HdfRow def defaultRowListClass(self): return HdfItemList # ---------------------------- def loopHDF(hdf, name=None): results = [] if name: o = hdf.getObj(name) else: o = hdf if o: o = o.child() while o: results.append(o) o = o.next() return results def loopKVHDF(hdf, name=None): results = [] if name: o = hdf.getObj(name) else: o = hdf if o: o = o.child() while o: results.append((o.name(), o.value())) o = o.next() return results class hdf_iterator: def __init__(self, hdf): self.hdf = hdf self.node = None if self.hdf: self.node = self.hdf.child() def __iter__(self): return self def next(self): if not self.node: raise StopIteration ret = self.node self.node = self.node.next() return ret class hdf_kv_iterator(hdf_iterator): def next(self): if not self.node: raise StopIteration ret = (self.node.name(), self.node.value()) self.node = self.node.next() return ret class hdf_key_iterator(hdf_iterator): def next(self): if not self.node: raise StopIteration ret = self.node.name() self.node = self.node.next() return ret class hdf_ko_iterator(hdf_iterator): def next(self): if not self.node: raise StopIteration ret = (self.node.name(), self.node) self.node = self.node.next() return ret # ---------------------------- def test(): import neo_util hdf = neo_util.HDF() hdf.setValue("foo","1") print eval_cs(hdf,"this should say 1 ===> ") if __name__ == "__main__": test() clearsilver-0.10.5/python/examples/base/log.py0000755001211700116100000000456010261037514016237 00000000000000#!/neo/opt/bin/python # log.py import sys, time, string DEV = "development" DEV_UPDATE = "update queries" DEV_SELECT = "select queries" DEV_REPORT = "report log" LOGGING_STATUS = { DEV : 1, DEV_UPDATE : 0, DEV_SELECT : 0, DEV_REPORT : 0} tstart = 0 def dlog(when,astr): global LOGGING_STATUS try: if LOGGING_STATUS[when]: log(astr) except KeyError: pass def tlog(astr): global tstart t = time.time() if tstart == 0: tstart = t time_stamp = "%5.5f" % (t-tstart) if len(astr): if astr[-1] == "\n": sys.stderr.write("[%s] %s" % (time_stamp, astr)) else: sys.stderr.write("[%s] %s\n" % (time_stamp, astr)) def orig_log(astr): if len(astr) > 1024: astr = astr[:1024] t = time.time() time_stamp = time.strftime("%m/%d %T", time.localtime(t)) if len(astr): if astr[-1] == "\n": sys.stderr.write("[%s] %s" % (time_stamp, astr)) else: sys.stderr.write("[%s] %s\n" % (time_stamp, astr)) # sys.stderr.flush() #---------------------------------------------------------------------- # static functions _gDebug = 0 _gFileDebug = 0 kBLACK = 0 kRED = 1 kGREEN = 2 kYELLOW = 3 kBLUE = 4 kMAGENTA = 5 kCYAN = 6 kWHITE = 7 kBRIGHT = 8 def ansicolor (str, fgcolor = None, bgcolor = None): o = "" if fgcolor: if fgcolor & kBRIGHT: bright = ';1' else: bright = '' o = o + '%c[3%d%sm' % (chr(27), fgcolor & 0x7, bright) if bgcolor: o = o + '%c[4%dm' % (chr(27), bgcolor) o = o + str if fgcolor or bgcolor: o = o + '%c[0m' % (chr(27)) return o def _log(*args): t = time.time() log_line = "" log_line = log_line + "[" + time.strftime("%m/%d %T", time.localtime(t)) + "] " l = [] for arg in args: l.append(str(arg)) log_line = log_line + string.join(l, " ") + "\n" sys.stderr.write(log_line) def warn(*args): apply(_log, args) def warnred(*args): args = tuple ([""] + list(args) + [""]) apply(_log, args) def log(*args): apply(_log, args) def logred(*args): if _gDebug>=1: args = tuple ([""] + list(args) + [""]) apply(_log, args) def debug(*args): if _gDebug>=2: apply(_log, args) def debugfull(): global _gDebug _gDebug = 2 def debugon(): global _gDebug _gDebug = 1 def debugoff(): global _gDebug _gDebug = 0 clearsilver-0.10.5/python/examples/base/odb.py0000755001211700116100000014425310261037514016226 00000000000000#!/usr/bin/env python # # odb.py # # Object Database Api # # Written by David Jeske , 2001/07. # Inspired by eGroups' sqldb.py originally written by Scott Hassan circa 1998. # # Copyright (C) 2001, by David Jeske and Neotonic # # Goals: # - a simple object-like interface to database data # - database independent (someday) # - relational-style "rigid schema definition" # - object style easy-access # # Example: # # import odb # # # define table # class AgentsTable(odb.Table): # def _defineRows(self): # self.d_addColumn("agent_id",kInteger,None,primarykey = 1,autoincrement = 1) # self.d_addColumn("login",kVarString,200,notnull=1) # self.d_addColumn("ticket_count",kIncInteger,None) # # if __name__ == "__main__": # # open database # ndb = MySQLdb.connect(host = 'localhost', # user='username', # passwd = 'password', # db='testdb') # db = Database(ndb) # tbl = AgentsTable(db,"agents") # # # create row # agent_row = tbl.newRow() # agent_row.login = "foo" # agent_row.save() # # # fetch row (must use primary key) # try: # get_row = tbl.fetchRow( ('agent_id', agent_row.agent_id) ) # except odb.eNoMatchingRows: # print "this is bad, we should have found the row" # # # fetch rows (can return empty list) # list_rows = tbl.fetchRows( ('login', "foo") ) # import string import sys, zlib from log import * import handle_error eNoSuchColumn = "odb.eNoSuchColumn" eNonUniqueMatchSpec = "odb.eNonUniqueMatchSpec" eNoMatchingRows = "odb.eNoMatchingRows" eInternalError = "odb.eInternalError" eInvalidMatchSpec = "odb.eInvalidMatchSpec" eInvalidData = "odb.eInvalidData" eUnsavedObjectLost = "odb.eUnsavedObjectLost" eDuplicateKey = "odb.eDuplicateKey" ##################################### # COLUMN TYPES ################ ###################### # typename ####################### size data means: # # # kInteger = "kInteger" # - kFixedString = "kFixedString" # size kVarString = "kVarString" # maxsize kBigString = "kBigString" # - kIncInteger = "kIncInteger" # - kDateTime = "kDateTime" kTimeStamp = "kTimeStamp" kReal = "kReal" DEBUG = 0 ############## # Database # # this will ultimately turn into a mostly abstract base class for # the DB adaptors for different database types.... # class Database: def __init__(self, db, debug=0): self._tables = {} self.db = db self._cursor = None self.compression_enabled = 0 self.debug = debug self.SQLError = None self.__defaultRowClass = self.defaultRowClass() self.__defaultRowListClass = self.defaultRowListClass() def defaultCursor(self): if self._cursor is None: self._cursor = self.db.cursor() return self._cursor def escape(self,str): raise "Unimplemented Error" def getDefaultRowClass(self): return self.__defaultRowClass def setDefaultRowClass(self, clss): self.__defaultRowClass = clss def getDefaultRowListClass(self): return self.__defaultRowListClass def setDefaultRowListClass(self, clss): self.__defaultRowListClass = clss def defaultRowClass(self): return Row def defaultRowListClass(self): # base type is list... return list def addTable(self, attrname, tblname, tblclass, rowClass = None, check = 0, create = 0, rowListClass = None): tbl = tblclass(self, tblname, rowClass=rowClass, check=check, create=create, rowListClass=rowListClass) self._tables[attrname] = tbl return tbl def close(self): for name, tbl in self._tables.items(): tbl.db = None self._tables = {} if self.db is not None: self.db.close() self.db = None def __getattr__(self, key): if key == "_tables": raise AttributeError, "odb.Database: not initialized properly, self._tables does not exist" try: table_dict = getattr(self,"_tables") return table_dict[key] except KeyError: raise AttributeError, "odb.Database: unknown attribute %s" % (key) def beginTransaction(self, cursor=None): if cursor is None: cursor = self.defaultCursor() dlog(DEV_UPDATE,"begin") cursor.execute("begin") def commitTransaction(self, cursor=None): if cursor is None: cursor = self.defaultCursor() dlog(DEV_UPDATE,"commit") cursor.execute("commit") def rollbackTransaction(self, cursor=None): if cursor is None: cursor = self.defaultCursor() dlog(DEV_UPDATE,"rollback") cursor.execute("rollback") ## ## schema creation code ## def createTables(self): tables = self.listTables() for attrname, tbl in self._tables.items(): tblname = tbl.getTableName() if tblname not in tables: print "table %s does not exist" % tblname tbl.createTable() else: invalidAppCols, invalidDBCols = tbl.checkTable() ## self.alterTableToMatch(tbl) def createIndices(self): indices = self.listIndices() for attrname, tbl in self._tables.items(): for indexName, (columns, unique) in tbl.getIndices().items(): if indexName in indices: continue tbl.createIndex(columns, indexName=indexName, unique=unique) def synchronizeSchema(self): tables = self.listTables() for attrname, tbl in self._tables.items(): tblname = tbl.getTableName() self.alterTableToMatch(tbl) def listTables(self, cursor=None): raise "Unimplemented Error" def listFieldsDict(self, table_name, cursor=None): raise "Unimplemented Error" def listFields(self, table_name, cursor=None): columns = self.listFieldsDict(table_name, cursor=cursor) return columns.keys() ########################################## # Table # class Table: def subclassinit(self): pass def __init__(self,database,table_name, rowClass = None, check = 0, create = 0, rowListClass = None): self.db = database self.__table_name = table_name if rowClass: self.__defaultRowClass = rowClass else: self.__defaultRowClass = database.getDefaultRowClass() if rowListClass: self.__defaultRowListClass = rowListClass else: self.__defaultRowListClass = database.getDefaultRowListClass() # get this stuff ready! self.__column_list = [] self.__vcolumn_list = [] self.__columns_locked = 0 self.__has_value_column = 0 self.__indices = {} # this will be used during init... self.__col_def_hash = None self.__vcol_def_hash = None self.__primary_key_list = None self.__relations_by_table = {} # ask the subclass to def his rows self._defineRows() # get ready to run! self.__lockColumnsAndInit() self.subclassinit() if create: self.createTable() if check: self.checkTable() def _colTypeToSQLType(self, colname, coltype, options): if coltype == kInteger: coltype = "integer" elif coltype == kFixedString: sz = options.get('size', None) if sz is None: coltype = 'char' else: coltype = "char(%s)" % sz elif coltype == kVarString: sz = options.get('size', None) if sz is None: coltype = 'varchar' else: coltype = "varchar(%s)" % sz elif coltype == kBigString: coltype = "text" elif coltype == kIncInteger: coltype = "integer" elif coltype == kDateTime: coltype = "datetime" elif coltype == kTimeStamp: coltype = "timestamp" elif coltype == kReal: coltype = "real" coldef = "%s %s" % (colname, coltype) if options.get('notnull', 0): coldef = coldef + " NOT NULL" if options.get('autoincrement', 0): coldef = coldef + " AUTO_INCREMENT" if options.get('unique', 0): coldef = coldef + " UNIQUE" # if options.get('primarykey', 0): coldef = coldef + " primary key" if options.get('default', None) is not None: coldef = coldef + " DEFAULT %s" % options.get('default') return coldef def getTableName(self): return self.__table_name def setTableName(self, tablename): self.__table_name = tablename def getIndices(self): return self.__indices def _createTableSQL(self): defs = [] for colname, coltype, options in self.__column_list: defs.append(self._colTypeToSQLType(colname, coltype, options)) defs = string.join(defs, ", ") primarykeys = self.getPrimaryKeyList() primarykey_str = "" if primarykeys: primarykey_str = ", PRIMARY KEY (" + string.join(primarykeys, ",") + ")" sql = "create table %s (%s %s)" % (self.__table_name, defs, primarykey_str) return sql def createTable(self, cursor=None): if cursor is None: cursor = self.db.defaultCursor() sql = self._createTableSQL() print "CREATING TABLE:", sql cursor.execute(sql) def dropTable(self, cursor=None): if cursor is None: cursor = self.db.defaultCursor() try: cursor.execute("drop table %s" % self.__table_name) # clean out the table except self.SQLError, reason: pass def renameTable(self, newTableName, cursor=None): if cursor is None: cursor = self.db.defaultCursor() try: cursor.execute("rename table %s to %s" % (self.__table_name, newTableName)) except sel.SQLError, reason: pass self.setTableName(newTableName) def getTableColumnsFromDB(self): return self.db.listFieldsDict(self.__table_name) def checkTable(self, warnflag=1): invalidDBCols = {} invalidAppCols = {} dbcolumns = self.getTableColumnsFromDB() for coldef in self.__column_list: colname = coldef[0] dbcoldef = dbcolumns.get(colname, None) if dbcoldef is None: invalidAppCols[colname] = 1 for colname, row in dbcolumns.items(): coldef = self.__col_def_hash.get(colname, None) if coldef is None: invalidDBCols[colname] = 1 if warnflag == 1: if invalidDBCols: print "----- WARNING ------------------------------------------" print " There are columns defined in the database schema that do" print " not match the application's schema." print " columns:", invalidDBCols.keys() print "--------------------------------------------------------" if invalidAppCols: print "----- WARNING ------------------------------------------" print " There are new columns defined in the application schema" print " that do not match the database's schema." print " columns:", invalidAppCols.keys() print "--------------------------------------------------------" return invalidAppCols, invalidDBCols def alterTableToMatch(self): raise "Unimplemented Error!" def addIndex(self, columns, indexName=None, unique=0): if indexName is None: indexName = self.getTableName() + "_index_" + string.join(columns, "_") self.__indices[indexName] = (columns, unique) def createIndex(self, columns, indexName=None, unique=0, cursor=None): if cursor is None: cursor = self.db.defaultCursor() cols = string.join(columns, ",") if indexName is None: indexName = self.getTableName() + "_index_" + string.join(columns, "_") uniquesql = "" if unique: uniquesql = " unique" sql = "create %s index %s on %s (%s)" % (uniquesql, indexName, self.getTableName(), cols) warn("creating index", sql) cursor.execute(sql) ## Column Definition def getColumnDef(self,column_name): try: return self.__col_def_hash[column_name] except KeyError: try: return self.__vcol_def_hash[column_name] except KeyError: raise eNoSuchColumn, "no column (%s) on table %s" % (column_name,self.__table_name) def getColumnList(self): return self.__column_list + self.__vcolumn_list def getAppColumnList(self): return self.__column_list def databaseSizeForData_ColumnName_(self,data,col_name): try: col_def = self.__col_def_hash[col_name] except KeyError: try: col_def = self.__vcol_def_hash[col_name] except KeyError: raise eNoSuchColumn, "no column (%s) on table %s" % (col_name,self.__table_name) c_name,c_type,c_options = col_def if c_type == kBigString: if c_options.get("compress_ok",0) and self.db.compression_enabled: z_size = len(zlib.compress(data,9)) r_size = len(data) if z_size < r_size: return z_size else: return r_size else: return len(data) else: # really simplistic database size computation: try: a = data[0] return len(data) except: return 4 def columnType(self, col_name): try: col_def = self.__col_def_hash[col_name] except KeyError: try: col_def = self.__vcol_def_hash[col_name] except KeyError: raise eNoSuchColumn, "no column (%s) on table %s" % (col_name,self.__table_name) c_name,c_type,c_options = col_def return c_type def convertDataForColumn(self,data,col_name): try: col_def = self.__col_def_hash[col_name] except KeyError: try: col_def = self.__vcol_def_hash[col_name] except KeyError: raise eNoSuchColumn, "no column (%s) on table %s" % (col_name,self.__table_name) c_name,c_type,c_options = col_def if c_type == kIncInteger: raise eInvalidData, "invalid operation for column (%s:%s) on table (%s)" % (col_name,c_type,self.__table_name) if c_type == kInteger: try: if data is None: data = 0 else: return long(data) except (ValueError,TypeError): raise eInvalidData, "invalid data (%s) for col (%s:%s) on table (%s)" % (repr(data),col_name,c_type,self.__table_name) elif c_type == kReal: try: if data is None: data = 0.0 else: return float(data) except (ValueError,TypeError): raise eInvalidData, "invalid data (%s) for col (%s:%s) on table (%s)" % (repr(data), col_name,c_type,self.__table_name) else: if type(data) == type(long(0)): return "%d" % data else: return str(data) def getPrimaryKeyList(self): return self.__primary_key_list def hasValueColumn(self): return self.__has_value_column def hasColumn(self,name): return self.__col_def_hash.has_key(name) def hasVColumn(self,name): return self.__vcol_def_hash.has_key(name) def _defineRows(self): raise "can't instantiate base odb.Table type, make a subclass and override _defineRows()" def __lockColumnsAndInit(self): # add a 'odb_value column' before we lockdown the table def if self.__has_value_column: self.d_addColumn("odb_value",kBigText,default='') self.__columns_locked = 1 # walk column list and make lookup hashes, primary_key_list, etc.. primary_key_list = [] col_def_hash = {} for a_col in self.__column_list: name,type,options = a_col col_def_hash[name] = a_col if options.has_key('primarykey'): primary_key_list.append(name) self.__col_def_hash = col_def_hash self.__primary_key_list = primary_key_list # setup the value columns! if (not self.__has_value_column) and (len(self.__vcolumn_list) > 0): raise "can't define vcolumns on table without ValueColumn, call d_addValueColumn() in your _defineRows()" vcol_def_hash = {} for a_col in self.__vcolumn_list: name,type,size_data,options = a_col vcol_def_hash[name] = a_col self.__vcol_def_hash = vcol_def_hash def __checkColumnLock(self): if self.__columns_locked: raise "can't change column definitions outside of subclass' _defineRows() method!" # table definition methods, these are only available while inside the # subclass's _defineRows method # # Ex: # # import odb # class MyTable(odb.Table): # def _defineRows(self): # self.d_addColumn("id",kInteger,primarykey = 1,autoincrement = 1) # self.d_addColumn("name",kVarString,120) # self.d_addColumn("type",kInteger, # enum_values = { 0 : "alive", 1 : "dead" } def d_addColumn(self,col_name,ctype,size=None,primarykey = 0, notnull = 0,indexed=0, default=None,unique=0,autoincrement=0,safeupdate=0, enum_values = None, no_export = 0, relations=None,compress_ok=0,int_date=0): self.__checkColumnLock() options = {} options['default'] = default if primarykey: options['primarykey'] = primarykey if unique: options['unique'] = unique if indexed: options['indexed'] = indexed self.addIndex((col_name,)) if safeupdate: options['safeupdate'] = safeupdate if autoincrement: options['autoincrement'] = autoincrement if notnull: options['notnull'] = notnull if size: options['size'] = size if no_export: options['no_export'] = no_export if int_date: if ctype != kInteger: raise eInvalidData, "can't flag columns int_date unless they are kInteger" else: options['int_date'] = int_date if enum_values: options['enum_values'] = enum_values inv_enum_values = {} for k,v in enum_values.items(): if inv_enum_values.has_key(v): raise eInvalidData, "enum_values paramater must be a 1 to 1 mapping for Table(%s)" % self.__table_name else: inv_enum_values[v] = k options['inv_enum_values'] = inv_enum_values if relations: options['relations'] = relations for a_relation in relations: table, foreign_column_name = a_relation if self.__relations_by_table.has_key(table): raise eInvalidData, "multiple relations for the same foreign table are not yet supported" self.__relations_by_table[table] = (col_name,foreign_column_name) if compress_ok: if ctype == kBigString: options['compress_ok'] = 1 else: raise eInvalidData, "only kBigString fields can be compress_ok=1" self.__column_list.append( (col_name,ctype,options) ) def d_addValueColumn(self): self.__checkColumnLock() self.__has_value_column = 1 def d_addVColumn(self,col_name,type,size=None,default=None): self.__checkColumnLock() if (not self.__has_value_column): raise "can't define VColumns on table without ValueColumn, call d_addValueColumn() first" options = {} if default: options['default'] = default if size: options['size'] = size self.__vcolumn_list.append( (col_name,type,options) ) ##################### # _checkColMatchSpec(col_match_spec,should_match_unique_row = 0) # # raise an error if the col_match_spec contains invalid columns, or # (in the case of should_match_unique_row) if it does not fully specify # a unique row. # # NOTE: we don't currently support where clauses with value column fields! # def _fixColMatchSpec(self,col_match_spec, should_match_unique_row = 0): if type(col_match_spec) == type([]): if type(col_match_spec[0]) != type((0,)): raise eInvalidMatchSpec, "invalid types in match spec, use [(,)..] or (,)" elif type(col_match_spec) == type((0,)): col_match_spec = [ col_match_spec ] elif type(col_match_spec) == type(None): if should_match_unique_row: raise eNonUniqueMatchSpec, "can't use a non-unique match spec (%s) here" % col_match_spec else: return None else: raise eInvalidMatchSpec, "invalid types in match spec, use [(,)..] or (,)" if should_match_unique_row: unique_column_lists = [] # first the primary key list my_primary_key_list = [] for a_key in self.__primary_key_list: my_primary_key_list.append(a_key) # then other unique keys for a_col in self.__column_list: col_name,a_type,options = a_col if options.has_key('unique'): unique_column_lists.append( (col_name, [col_name]) ) unique_column_lists.append( ('primary_key', my_primary_key_list) ) new_col_match_spec = [] for a_col in col_match_spec: name,val = a_col # newname = string.lower(name) # what is this doing?? - jeske newname = name if not self.__col_def_hash.has_key(newname): raise eNoSuchColumn, "no such column in match spec: '%s'" % newname new_col_match_spec.append( (newname,val) ) if should_match_unique_row: for name,a_list in unique_column_lists: try: a_list.remove(newname) except ValueError: # it's okay if they specify too many columns! pass if should_match_unique_row: for name,a_list in unique_column_lists: if len(a_list) == 0: # we matched at least one unique colum spec! # log("using unique column (%s) for query %s" % (name,col_match_spec)) return new_col_match_spec raise eNonUniqueMatchSpec, "can't use a non-unique match spec (%s) here" % col_match_spec return new_col_match_spec def __buildWhereClause (self, col_match_spec,other_clauses = None): sql_where_list = [] if not col_match_spec is None: for m_col in col_match_spec: m_col_name,m_col_val = m_col c_name,c_type,c_options = self.__col_def_hash[m_col_name] if c_type in (kIncInteger, kInteger): try: m_col_val_long = long(m_col_val) except ValueError: raise ValueError, "invalid literal for long(%s) in table %s" % (repr(m_col_val),self.__table_name) sql_where_list.append("%s = %d" % (c_name, m_col_val_long)) elif c_type == kReal: try: m_col_val_float = float(m_col_val) except ValueError: raise ValueError, "invalid literal for float(%s) is table %s" % (repr(m_col_val), self.__table_name) sql_where_list.append("%s = %s" % (c_name, m_col_val_float)) else: sql_where_list.append("%s = '%s'" % (c_name, self.db.escape(m_col_val))) if other_clauses is None: pass elif type(other_clauses) == type(""): sql_where_list = sql_where_list + [other_clauses] elif type(other_clauses) == type([]): sql_where_list = sql_where_list + other_clauses else: raise eInvalidData, "unknown type of extra where clause: %s" % repr(other_clauses) return sql_where_list def __fetchRows(self,col_match_spec,cursor = None, where = None, order_by = None, limit_to = None, skip_to = None, join = None): if cursor is None: cursor = self.db.defaultCursor() # build column list sql_columns = [] for name,t,options in self.__column_list: sql_columns.append(name) # build join information joined_cols = [] joined_cols_hash = {} join_clauses = [] if not join is None: for a_table,retrieve_foreign_cols in join: try: my_col,foreign_col = self.__relations_by_table[a_table] for a_col in retrieve_foreign_cols: full_col_name = "%s.%s" % (my_col,a_col) joined_cols_hash[full_col_name] = 1 joined_cols.append(full_col_name) sql_columns.append( full_col_name ) join_clauses.append(" left join %s as %s on %s=%s " % (a_table,my_col,my_col,foreign_col)) except KeyError: eInvalidJoinSpec, "can't find table %s in defined relations for %s" % (a_table,self.__table_name) # start buildling SQL sql = "select %s from %s" % (string.join(sql_columns,","), self.__table_name) # add join clause if join_clauses: sql = sql + string.join(join_clauses," ") # add where clause elements sql_where_list = self.__buildWhereClause (col_match_spec,where) if sql_where_list: sql = sql + " where %s" % (string.join(sql_where_list," and ")) # add order by clause if order_by: sql = sql + " order by %s " % string.join(order_by,",") # add limit if not limit_to is None: if not skip_to is None: # log("limit,skip = %s,%s" % (limit_to,skip_to)) if self.db.db.__module__ == "sqlite.main": sql = sql + " limit %s offset %s " % (limit_to,skip_to) else: sql = sql + " limit %s, %s" % (skip_to,limit_to) else: sql = sql + " limit %s" % limit_to else: if not skip_to is None: raise eInvalidData, "can't specify skip_to without limit_to in MySQL" dlog(DEV_SELECT,sql) cursor.execute(sql) # create defaultRowListClass instance... return_rows = self.__defaultRowListClass() # should do fetchmany! all_rows = cursor.fetchall() for a_row in all_rows: data_dict = {} col_num = 0 # for a_col in cursor.description: # (name,type_code,display_size,internal_size,precision,scale,null_ok) = a_col for name in sql_columns: if self.__col_def_hash.has_key(name) or joined_cols_hash.has_key(name): # only include declared columns! if self.__col_def_hash.has_key(name): c_name,c_type,c_options = self.__col_def_hash[name] if c_type == kBigString and c_options.get("compress_ok",0) and a_row[col_num]: try: a_col_data = zlib.decompress(a_row[col_num]) except zlib.error: a_col_data = a_row[col_num] data_dict[name] = a_col_data elif c_type == kInteger or c_type == kIncInteger: value = a_row[col_num] if not value is None: data_dict[name] = int(value) else: data_dict[name] = None else: data_dict[name] = a_row[col_num] else: data_dict[name] = a_row[col_num] col_num = col_num + 1 newrowobj = self.__defaultRowClass(self,data_dict,joined_cols = joined_cols) return_rows.append(newrowobj) return return_rows def __deleteRow(self,a_row,cursor = None): if cursor is None: cursor = self.db.defaultCursor() # build the where clause! match_spec = a_row.getPKMatchSpec() sql_where_list = self.__buildWhereClause (match_spec) sql = "delete from %s where %s" % (self.__table_name, string.join(sql_where_list," and ")) dlog(DEV_UPDATE,sql) cursor.execute(sql) def __updateRowList(self,a_row_list,cursor = None): if cursor is None: cursor = self.db.defaultCursor() for a_row in a_row_list: update_list = a_row.changedList() # build the set list! sql_set_list = [] for a_change in update_list: col_name,col_val,col_inc_val = a_change c_name,c_type,c_options = self.__col_def_hash[col_name] if c_type != kIncInteger and col_val is None: sql_set_list.append("%s = NULL" % c_name) elif c_type == kIncInteger and col_inc_val is None: sql_set_list.append("%s = 0" % c_name) else: if c_type == kInteger: sql_set_list.append("%s = %d" % (c_name, long(col_val))) elif c_type == kIncInteger: sql_set_list.append("%s = %s + %d" % (c_name,c_name,long(col_inc_val))) elif c_type == kBigString and c_options.get("compress_ok",0) and self.db.compression_enabled: compressed_data = zlib.compress(col_val,9) if len(compressed_data) < len(col_val): sql_set_list.append("%s = '%s'" % (c_name, self.db.escape(compressed_data))) else: sql_set_list.append("%s = '%s'" % (c_name, self.db.escape(col_val))) elif c_type == kReal: sql_set_list.append("%s = %s" % (c_name,float(col_val))) else: sql_set_list.append("%s = '%s'" % (c_name, self.db.escape(col_val))) # build the where clause! match_spec = a_row.getPKMatchSpec() sql_where_list = self.__buildWhereClause (match_spec) if sql_set_list: sql = "update %s set %s where %s" % (self.__table_name, string.join(sql_set_list,","), string.join(sql_where_list," and ")) dlog(DEV_UPDATE,sql) try: cursor.execute(sql) except Exception, reason: if string.find(str(reason), "Duplicate entry") != -1: raise eDuplicateKey, reason raise Exception, reason a_row.markClean() def __insertRow(self,a_row_obj,cursor = None,replace=0): if cursor is None: cursor = self.db.defaultCursor() sql_col_list = [] sql_data_list = [] auto_increment_column_name = None for a_col in self.__column_list: name,type,options = a_col try: data = a_row_obj[name] sql_col_list.append(name) if data is None: sql_data_list.append("NULL") else: if type == kInteger or type == kIncInteger: sql_data_list.append("%d" % data) elif type == kBigString and options.get("compress_ok",0) and self.db.compression_enabled: compressed_data = zlib.compress(data,9) if len(compressed_data) < len(data): sql_data_list.append("'%s'" % self.db.escape(compressed_data)) else: sql_data_list.append("'%s'" % self.db.escape(data)) elif type == kReal: sql_data_list.append("%s" % data) else: sql_data_list.append("'%s'" % self.db.escape(data)) except KeyError: if options.has_key("autoincrement"): if auto_increment_column_name: raise eInternalError, "two autoincrement columns (%s,%s) in table (%s)" % (auto_increment_column_name, name,self.__table_name) else: auto_increment_column_name = name if replace: sql = "replace into %s (%s) values (%s)" % (self.__table_name, string.join(sql_col_list,","), string.join(sql_data_list,",")) else: sql = "insert into %s (%s) values (%s)" % (self.__table_name, string.join(sql_col_list,","), string.join(sql_data_list,",")) dlog(DEV_UPDATE,sql) try: cursor.execute(sql) except Exception, reason: # sys.stderr.write("errror in statement: " + sql + "\n") log("error in statement: " + sql + "\n") if string.find(str(reason), "Duplicate entry") != -1: raise eDuplicateKey, reason raise Exception, reason if auto_increment_column_name: if cursor.__module__ == "sqlite.main": a_row_obj[auto_increment_column_name] = cursor.lastrowid elif cursor.__module__ == "MySQLdb.cursors": a_row_obj[auto_increment_column_name] = cursor.insert_id() else: # fallback to acting like mysql a_row_obj[auto_increment_column_name] = cursor.insert_id() # ---------------------------------------------------- # Helper methods for Rows... # ---------------------------------------------------- ##################### # r_deleteRow(a_row_obj,cursor = None) # # normally this is called from within the Row "delete()" method # but you can call it yourself if you want # def r_deleteRow(self,a_row_obj, cursor = None): curs = cursor self.__deleteRow(a_row_obj, cursor = curs) ##################### # r_updateRow(a_row_obj,cursor = None) # # normally this is called from within the Row "save()" method # but you can call it yourself if you want # def r_updateRow(self,a_row_obj, cursor = None): curs = cursor self.__updateRowList([a_row_obj], cursor = curs) ##################### # InsertRow(a_row_obj,cursor = None) # # normally this is called from within the Row "save()" method # but you can call it yourself if you want # def r_insertRow(self,a_row_obj, cursor = None,replace=0): curs = cursor self.__insertRow(a_row_obj, cursor = curs,replace=replace) # ---------------------------------------------------- # Public Methods # ---------------------------------------------------- ##################### # deleteRow(col_match_spec) # # The col_match_spec paramaters must include all primary key columns. # # Ex: # a_row = tbl.fetchRow( ("order_id", 1) ) # a_row = tbl.fetchRow( [ ("order_id", 1), ("enterTime", now) ] ) def deleteRow(self,col_match_spec, where=None): n_match_spec = self._fixColMatchSpec(col_match_spec) cursor = self.db.defaultCursor() # build sql where clause elements sql_where_list = self.__buildWhereClause (n_match_spec,where) if not sql_where_list: return sql = "delete from %s where %s" % (self.__table_name, string.join(sql_where_list," and ")) dlog(DEV_UPDATE,sql) cursor.execute(sql) ##################### # fetchRow(col_match_spec) # # The col_match_spec paramaters must include all primary key columns. # # Ex: # a_row = tbl.fetchRow( ("order_id", 1) ) # a_row = tbl.fetchRow( [ ("order_id", 1), ("enterTime", now) ] ) def fetchRow(self, col_match_spec, cursor = None): n_match_spec = self._fixColMatchSpec(col_match_spec, should_match_unique_row = 1) rows = self.__fetchRows(n_match_spec, cursor = cursor) if len(rows) == 0: raise eNoMatchingRows, "no row matches %s" % repr(n_match_spec) if len(rows) > 1: raise eInternalError, "unique where clause shouldn't return > 1 row" return rows[0] ##################### # fetchRows(col_match_spec) # # Ex: # a_row_list = tbl.fetchRows( ("order_id", 1) ) # a_row_list = tbl.fetchRows( [ ("order_id", 1), ("enterTime", now) ] ) def fetchRows(self, col_match_spec = None, cursor = None, where = None, order_by = None, limit_to = None, skip_to = None, join = None): n_match_spec = self._fixColMatchSpec(col_match_spec) return self.__fetchRows(n_match_spec, cursor = cursor, where = where, order_by = order_by, limit_to = limit_to, skip_to = skip_to, join = join) def fetchRowCount (self, col_match_spec = None, cursor = None, where = None): n_match_spec = self._fixColMatchSpec(col_match_spec) sql_where_list = self.__buildWhereClause (n_match_spec,where) sql = "select count(*) from %s" % self.__table_name if sql_where_list: sql = "%s where %s" % (sql,string.join(sql_where_list," and ")) if cursor is None: cursor = self.db.defaultCursor() dlog(DEV_SELECT,sql) cursor.execute(sql) try: count, = cursor.fetchone() except TypeError: count = 0 return count ##################### # fetchAllRows() # # Ex: # a_row_list = tbl.fetchRows( ("order_id", 1) ) # a_row_list = tbl.fetchRows( [ ("order_id", 1), ("enterTime", now) ] ) def fetchAllRows(self): try: return self.__fetchRows([]) except eNoMatchingRows: # else return empty list... return self.__defaultRowListClass() def newRow(self,replace=0): row = self.__defaultRowClass(self,None,create=1,replace=replace) for (cname, ctype, opts) in self.__column_list: if opts['default'] is not None and ctype is not kIncInteger: row[cname] = opts['default'] return row class Row: __instance_data_locked = 0 def subclassinit(self): pass def __init__(self,_table,data_dict,create=0,joined_cols = None,replace=0): self._inside_getattr = 0 # stop recursive __getattr__ self._table = _table self._should_insert = create or replace self._should_replace = replace self._rowInactive = None self._joinedRows = [] self.__pk_match_spec = None self.__vcoldata = {} self.__inc_coldata = {} self.__joined_cols_dict = {} for a_col in joined_cols or []: self.__joined_cols_dict[a_col] = 1 if create: self.__coldata = {} else: if type(data_dict) != type({}): raise eInternalError, "rowdict instantiate with bad data_dict" self.__coldata = data_dict self.__unpackVColumn() self.markClean() self.subclassinit() self.__instance_data_locked = 1 def joinRowData(self,another_row): self._joinedRows.append(another_row) def getPKMatchSpec(self): return self.__pk_match_spec def markClean(self): self.__vcolchanged = 0 self.__colchanged_dict = {} for key in self.__inc_coldata.keys(): self.__coldata[key] = self.__coldata.get(key, 0) + self.__inc_coldata[key] self.__inc_coldata = {} if not self._should_insert: # rebuild primary column match spec new_match_spec = [] for col_name in self._table.getPrimaryKeyList(): try: rdata = self[col_name] except KeyError: raise eInternalError, "must have primary key data filled in to save %s:Row(col:%s)" % (self._table.getTableName(),col_name) new_match_spec.append( (col_name, rdata) ) self.__pk_match_spec = new_match_spec def __unpackVColumn(self): if self._table.hasValueColumn(): pass def __packVColumn(self): if self._table.hasValueColumn(): pass ## ----- utility stuff ---------------------------------- def __del__(self): # check for unsaved changes changed_list = self.changedList() if len(changed_list): info = "unsaved Row for table (%s) lost, call discard() to avoid this error. Lost changes: %s\n" % (self._table.getTableName(), repr(changed_list)[:256]) if 0: raise eUnsavedObjectLost, info else: sys.stderr.write(info) def __repr__(self): return "Row from (%s): %s" % (self._table.getTableName(),repr(self.__coldata) + repr(self.__vcoldata)) ## ---- class emulation -------------------------------- def __getattr__(self,key): if self._inside_getattr: raise AttributeError, "recursively called __getattr__ (%s,%s)" % (key,self._table.getTableName()) try: self._inside_getattr = 1 try: return self[key] except KeyError: if self._table.hasColumn(key) or self._table.hasVColumn(key): return None else: raise AttributeError, "unknown field '%s' in Row(%s)" % (key,self._table.getTableName()) finally: self._inside_getattr = 0 def __setattr__(self,key,val): if not self.__instance_data_locked: self.__dict__[key] = val else: my_dict = self.__dict__ if my_dict.has_key(key): my_dict[key] = val else: # try and put it into the rowdata try: self[key] = val except KeyError, reason: raise AttributeError, reason ## ---- dict emulation --------------------------------- def __getitem__(self,key): self.checkRowActive() try: c_type = self._table.columnType(key) except eNoSuchColumn, reason: # Ugh, this sucks, we can't determine the type for a joined # row, so we just default to kVarString and let the code below # determine if this is a joined column or not c_type = kVarString if c_type == kIncInteger: c_data = self.__coldata.get(key, 0) if c_data is None: c_data = 0 i_data = self.__inc_coldata.get(key, 0) if i_data is None: i_data = 0 return c_data + i_data try: return self.__coldata[key] except KeyError: try: return self.__vcoldata[key] except KeyError: for a_joined_row in self._joinedRows: try: return a_joined_row[key] except KeyError: pass raise KeyError, "unknown column %s in %s" % (key,self) def __setitem__(self,key,data): self.checkRowActive() try: newdata = self._table.convertDataForColumn(data,key) except eNoSuchColumn, reason: raise KeyError, reason if self._table.hasColumn(key): self.__coldata[key] = newdata self.__colchanged_dict[key] = 1 elif self._table.hasVColumn(key): self.__vcoldata[key] = newdata self.__vcolchanged = 1 else: for a_joined_row in self._joinedRows: try: a_joined_row[key] = data return except KeyError: pass raise KeyError, "unknown column name %s" % key def __delitem__(self,key,data): self.checkRowActive() if self.table.hasVColumn(key): del self.__vcoldata[key] else: for a_joined_row in self._joinedRows: try: del a_joined_row[key] return except KeyError: pass raise KeyError, "unknown column name %s" % key def copyFrom(self,source): for name,t,options in self._table.getColumnList(): if not options.has_key("autoincrement"): self[name] = source[name] # make sure that .keys(), and .items() come out in a nice order! def keys(self): self.checkRowActive() key_list = [] for name,t,options in self._table.getColumnList(): key_list.append(name) for name in self.__joined_cols_dict.keys(): key_list.append(name) for a_joined_row in self._joinedRows: key_list = key_list + a_joined_row.keys() return key_list def items(self): self.checkRowActive() item_list = [] for name,t,options in self._table.getColumnList(): item_list.append( (name,self[name]) ) for name in self.__joined_cols_dict.keys(): item_list.append( (name,self[name]) ) for a_joined_row in self._joinedRows: item_list = item_list + a_joined_row.items() return item_list def values(elf): self.checkRowActive() value_list = self.__coldata.values() + self.__vcoldata.values() for a_joined_row in self._joinedRows: value_list = value_list + a_joined_row.values() return value_list def __len__(self): self.checkRowActive() my_len = len(self.__coldata) + len(self.__vcoldata) for a_joined_row in self._joinedRows: my_len = my_len + len(a_joined_row) return my_len def has_key(self,key): self.checkRowActive() if self.__coldata.has_key(key) or self.__vcoldata.has_key(key): return 1 else: for a_joined_row in self._joinedRows: if a_joined_row.has_key(key): return 1 return 0 def get(self,key,default = None): self.checkRowActive() if self.__coldata.has_key(key): return self.__coldata[key] elif self.__vcoldata.has_key(key): return self.__vcoldata[key] else: for a_joined_row in self._joinedRows: try: return a_joined_row.get(key,default) except eNoSuchColumn: pass if self._table.hasColumn(key): return default raise eNoSuchColumn, "no such column %s" % key def inc(self,key,count=1): self.checkRowActive() if self._table.hasColumn(key): try: self.__inc_coldata[key] = self.__inc_coldata[key] + count except KeyError: self.__inc_coldata[key] = count self.__colchanged_dict[key] = 1 else: raise AttributeError, "unknown field '%s' in Row(%s)" % (key,self._table.getTableName()) ## ---------------------------------- ## real interface def fillDefaults(self): for field_def in self._table.fieldList(): name,type,size,options = field_def if options.has_key("default"): self[name] = options["default"] ############### # changedList() # # returns a list of tuples for the columns which have changed # # changedList() -> [ ('name', 'fred'), ('age', 20) ] def changedList(self): if self.__vcolchanged: self.__packVColumn() changed_list = [] for a_col in self.__colchanged_dict.keys(): changed_list.append( (a_col,self.get(a_col,None),self.__inc_coldata.get(a_col,None)) ) return changed_list def discard(self): self.__coldata = None self.__vcoldata = None self.__colchanged_dict = {} self.__vcolchanged = 0 def delete(self,cursor = None): self.checkRowActive() fromTable = self._table curs = cursor fromTable.r_deleteRow(self,cursor=curs) self._rowInactive = "deleted" def save(self,cursor = None): toTable = self._table self.checkRowActive() if self._should_insert: toTable.r_insertRow(self,replace=self._should_replace) self._should_insert = 0 self._should_replace = 0 self.markClean() # rebuild the primary key list else: curs = cursor toTable.r_updateRow(self,cursor = curs) # the table will mark us clean! # self.markClean() def checkRowActive(self): if self._rowInactive: raise eInvalidData, "row is inactive: %s" % self._rowInactive def databaseSizeForColumn(self,key): return self._table.databaseSizeForData_ColumnName_(self[key],key) if __name__ == "__main__": print "run odb_test.py" clearsilver-0.10.5/python/examples/base/odb_mysql.py0000755001211700116100000000311610261037514017443 00000000000000#! /usr/bin/env python """ usage: %(progname)s [args] """ # import startscript; startscript.init(__name__) import os, sys, string, time, getopt from log import * import odb import MySQLdb class Database(odb.Database): def __init__(self,db, debug=0): odb.Database.__init__(self, db, debug=debug) self.SQLError = MySQLdb.Error def escape(self,str): if str is None: return None return MySQLdb.escape_string(str) def listTables(self, cursor=None): if cursor is None: cursor = self.defaultCursor() cursor.execute("show tables") rows = cursor.fetchall() tables = [] for row in rows: tables.append(row[0]) return tables def listIndices(self, cursor=None): return [] def listFieldsDict(self, table_name, cursor=None): if cursor is None: cursor = self.defaultCursor() sql = "show columns from %s" % table_name cursor.execute(sql) rows = cursor.fetchall() columns = {} for row in rows: colname = row[0] columns[colname] = row return columns def alterTableToMatch(self): invalidAppCols, invalidDBCols = self.checkTable() if not invalidAppCols: return defs = [] for colname in invalidAppCols.keys(): col = self.getColumnDef(colname) colname = col[0] coltype = col[1] options = col[2] defs.append(self.colTypeToSQLType(colname, coltype, options)) defs = string.join(defs, ", ") sql = "alter table %s add column " % self.getTableName() sql = sql + "(" + defs + ")" print sql cur = self.db.defaultCursor() cur.execute(sql) clearsilver-0.10.5/python/examples/base/odb_sqlite.py0000755001211700116100000000776110261037514017611 00000000000000#! /usr/bin/env python """ usage: %(progname)s [args] """ import os, sys, string, time, getopt from log import * import odb import sqlite import re # --- these are using for removing nulls from strings # --- because sqlite can't handle them def escape_string(str): def subfn(m): c = m.group(0) return "%%%02X" % ord(c) return re.sub("('|\0|%)",subfn,str) def unescape_string(str): def subfn(m): hexnum = int(m.group(1),16) return "%c" % hexnum return re.sub("%(..)",subfn,str) class Database(odb.Database): def __init__(self,db, debug=0): odb.Database.__init__(self, db, debug=debug) self.SQLError = sqlite.Error def escape(self,str): if str is None: return None elif type(str) == type(""): return string.replace(str,"'","''") elif type(str) == type(1): return str else: raise "unknown column data type: %s" % type(str) def listTables(self, cursor=None): if cursor is None: cursor = self.defaultCursor() cursor.execute("select name from sqlite_master where type='table'") rows = cursor.fetchall() tables = [] for row in rows: tables.append(row[0]) return tables def listIndices(self, cursor=None): if cursor is None: cursor = self.defaultCursor() cursor.execute("select name from sqlite_master where type='index'") rows = cursor.fetchall() tables = [] for row in rows: tables.append(row[0]) return tables def listFieldsDict(self, table_name, cursor=None): if cursor is None: cursor = self.defaultCursor() sql = "pragma table_info(%s)" % table_name cursor.execute(sql) rows = cursor.fetchall() columns = {} for row in rows: colname = row[1] columns[colname] = row return columns def _tableCreateStatement(self, table_name, cursor=None): if cursor is None: cursor = self.defaultCursor() sql = "select sql from sqlite_master where type='table' and name='%s'" % table_name print sql cursor.execute(sql) row = cursor.fetchone() sqlstatement = row[0] return sqlstatement def alterTableToMatch(self, table): tableName = table.getTableName() tmpTableName = tableName + "_" + str(os.getpid()) invalidAppCols, invalidDBCols = table.checkTable(warnflag=0) ## if invalidAppCols or invalidDBCols: ## return if not invalidAppCols and not invalidDBCols: return oldcols = self.listFieldsDict(tableName) # tmpcols = oldcols.keys() tmpcols = [] newcols = table.getAppColumnList() for colname, coltype, options in newcols: if oldcols.has_key(colname): tmpcols.append(colname) tmpcolnames = string.join(tmpcols, ",") statements = [] sql = "begin transaction" statements.append(sql) sql = "create temporary table %s (%s)" % (tmpTableName, tmpcolnames) statements.append(sql) sql = "insert into %s select %s from %s" % (tmpTableName, tmpcolnames, tableName) statements.append(sql) sql = "drop table %s" % tableName statements.append(sql) sql = table._createTableSQL() statements.append(sql) sql = "insert into %s(%s) select %s from %s" % (tableName, tmpcolnames, tmpcolnames, tmpTableName) statements.append(sql) sql = "drop table %s" % tmpTableName statements.append(sql) sql = "commit" statements.append(sql) cur = self.defaultCursor() for statement in statements: # print statement cur.execute(statement) def test(): pass def usage(progname): print __doc__ % vars() def main(argv, stdout, environ): progname = argv[0] optlist, args = getopt.getopt(argv[1:], "", ["help", "test", "debug"]) testflag = 0 if len(args) == 0: usage(progname) return for (field, val) in optlist: if field == "--help": usage(progname) return elif field == "--debug": debugfull() elif field == "--test": testflag = 1 if testflag: test() return if __name__ == "__main__": main(sys.argv, sys.stdout, os.environ) clearsilver-0.10.5/python/examples/base/odb_test.py0000755001211700116100000002022110261037514017251 00000000000000#!/usr/bin/env python from odb import * ## ----------------------------------------------------------------------- ## T E S T S ## ----------------------------------------------------------------------- import MySQLdb import odb_mysql import sqlite import odb_sqlite def TEST(output=log): LOGGING_STATUS[DEV_SELECT] = 1 LOGGING_STATUS[DEV_UPDATE] = 1 print "------ TESTING MySQLdb ---------" rdb = MySQLdb.connect(host = 'localhost',user='root', passwd = '', db='testdb') ndb = MySQLdb.connect(host = 'localhost',user='trakken', passwd = 'trakpas', db='testdb') cursor = rdb.cursor() output("drop table agents") try: cursor.execute("drop table agents") # clean out the table except: pass output("creating table") SQL = """ create table agents ( agent_id integer not null primary key auto_increment, login varchar(200) not null, unique (login), ext_email varchar(200) not null, hashed_pw varchar(20) not null, name varchar(200), auth_level integer default 0, ticket_count integer default 0) """ cursor.execute(SQL) db = odb_mysql.Database(ndb) TEST_DATABASE(rdb,db,output=output) print "------ TESTING sqlite ----------" rdb = sqlite.connect("/tmp/test.db",autocommit=1) cursor = rdb.cursor() try: cursor.execute("drop table agents") except: pass SQL = """ create table agents ( agent_id integer primary key, login varchar(200) not null, ext_email varchar(200) not null, hashed_pw varchar(20), name varchar(200), auth_level integer default 0, ticket_count integer default 0)""" cursor.execute(SQL) rdb = sqlite.connect("/tmp/test.db",autocommit=1) ndb = sqlite.connect("/tmp/test.db",autocommit=1) db = odb_sqlite.Database(ndb) TEST_DATABASE(rdb,db,output=output,is_mysql=0) def TEST_DATABASE(rdb,db,output=log,is_mysql=1): cursor = rdb.cursor() class AgentsTable(Table): def _defineRows(self): self.d_addColumn("agent_id",kInteger,None,primarykey = 1,autoincrement = 1) self.d_addColumn("login",kVarString,200,notnull=1) self.d_addColumn("ext_email",kVarString,200,notnull=1) self.d_addColumn("hashed_pw",kVarString,20,notnull=1) self.d_addColumn("name",kBigString,compress_ok=1) self.d_addColumn("auth_level",kInteger,None) self.d_addColumn("ticket_count",kIncInteger,None) tbl = AgentsTable(db,"agents") TEST_INSERT_COUNT = 5 # --------------------------------------------------------------- # make sure we can catch a missing row try: a_row = tbl.fetchRow( ("agent_id", 1000) ) raise "test error" except eNoMatchingRows: pass output("PASSED! fetch missing row test") # -------------------------------------------------------------- # create new rows and insert them for n in range(TEST_INSERT_COUNT): new_id = n + 1 newrow = tbl.newRow() newrow.name = "name #%d" % new_id newrow.login = "name%d" % new_id newrow.ext_email = "%d@name" % new_id newrow.save() if newrow.agent_id != new_id: raise "new insert id (%s) does not match expected value (%d)" % (newrow.agent_id,new_id) output("PASSED! autoinsert test") # -------------------------------------------------------------- # fetch one row a_row = tbl.fetchRow( ("agent_id", 1) ) if a_row.name != "name #1": raise "row data incorrect" output("PASSED! fetch one row test") # --------------------------------------------------------------- # don't change and save it # (i.e. the "dummy cursor" string should never be called!) # try: a_row.save(cursor = "dummy cursor") except AttributeError, reason: raise "row tried to access cursor on save() when no changes were made!" output("PASSED! don't save when there are no changed") # --------------------------------------------------------------- # change, save, load, test a_row.auth_level = 10 a_row.save() b_row = tbl.fetchRow( ("agent_id", 1) ) if b_row.auth_level != 10: log(repr(b_row)) raise "save and load failed" output("PASSED! change, save, load") # --------------------------------------------------------------- # replace repl_row = tbl.newRow(replace=1) repl_row.agent_id = a_row.agent_id repl_row.login = a_row.login + "-" + a_row.login repl_row.ext_email = "foo" repl_row.save() b_row = tbl.fetchRow( ("agent_id", a_row.agent_id) ) if b_row.login != repl_row.login: raise "replace failed" output("PASSED! replace") # -------------------------------------------------------------- # access unknown dict item try: a = a_row["UNKNOWN_ATTRIBUTE"] raise "test error" except KeyError, reason: pass try: a_row["UNKNOWN_ATTRIBUTE"] = 1 raise "test error" except KeyError, reason: pass output("PASSED! unknown dict item exception") # -------------------------------------------------------------- # access unknown attribute try: a = a_row.UNKNOWN_ATTRIBUTE raise "test error" except AttributeError, reason: pass try: a_row.UNKNOWN_ATTRIBUTE = 1 raise "test error" except AttributeError, reason: pass output("PASSED! unknown attribute exception") # -------------------------------------------------------------- # use wrong data for column type try: a_row.agent_id = "this is a string" raise "test error" except eInvalidData, reason: pass output("PASSED! invalid data for column type") # -------------------------------------------------------------- # fetch 1 rows rows = tbl.fetchRows( ('agent_id', 1) ) if len(rows) != 1: raise "fetchRows() did not return 1 row!" % (TEST_INSERT_COUNT) output("PASSED! fetch one row") # -------------------------------------------------------------- # fetch All rows rows = tbl.fetchAllRows() if len(rows) != TEST_INSERT_COUNT: for a_row in rows: output(repr(a_row)) raise "fetchAllRows() did not return TEST_INSERT_COUNT(%d) rows!" % (TEST_INSERT_COUNT) output("PASSED! fetchall rows") # -------------------------------------------------------------- # delete row object row = tbl.fetchRow( ('agent_id', 1) ) row.delete() try: row = tbl.fetchRow( ('agent_id', 1) ) raise "delete failed to delete row!" except eNoMatchingRows: pass # -------------------------------------------------------------- # table deleteRow() call row = tbl.fetchRow( ('agent_id',2) ) tbl.deleteRow( ('agent_id', 2) ) try: row = tbl.fetchRow( ('agent_id',2) ) raise "table delete failed" except eNoMatchingRows: pass # -------------------------------------------------------------- # table deleteRow() call row = tbl.fetchRow( ('agent_id',3) ) if row.databaseSizeForColumn('name') != len(row.name): raise "databaseSizeForColumn('name') failed" # -------------------------------------------------------------- # test inc fields row = tbl.newRow() new_id = 1092 row.name = "name #%d" % new_id row.login = "name%d" % new_id row.ext_email = "%d@name" % new_id row.inc('ticket_count') row.save() new_id = row.agent_id trow = tbl.fetchRow( ('agent_id',new_id) ) if trow.ticket_count != 1: raise "ticket_count didn't inc!" row.inc('ticket_count', count=2) row.save() trow = tbl.fetchRow( ('agent_id',new_id) ) if trow.ticket_count != 3: raise "ticket_count wrong, expected 3, got %d" % trow.ticket_count trow.inc('ticket_count') trow.save() if trow.ticket_count != 4: raise "ticket_count wrong, expected 4, got %d" % trow.ticket_count output("\n==== ALL TESTS PASSED ====") if __name__ == "__main__": TEST() clearsilver-0.10.5/python/examples/base/profiler.py0000755001211700116100000000377010261037514017302 00000000000000 import time import who_calls import neo_cgi PROFILER_DATA = [] PROFILER_START = 0 PROFILER_ENABLED = 0 PROFILER_DEPTH = 0 def enable(): global PROFILER_START global PROFILER_ENABLED global PROFILER_DATA PROFILER_START = time.time() PROFILER_ENABLED = 1 PROFILER_DATA = [] def disable(): global PROFILER_START global PROFILER_ENABLED global PROFILER_DATA PROFILER_START = 0 PROFILER_ENABLED = 0 PROFILER_DATA = [] def hdfExport(prefix, hdf): global PROFILER_DATA n = 0 for p in PROFILER_DATA: hdf.setValue("%s.%d.when" % (prefix, n), "%5.2f" % (p.when)) hdf.setValue("%s.%d.time" % (prefix, n), "%5.2f" % (p.length)) hdf.setValue("%s.%d.klass" % (prefix, n), p.klass) hdf.setValue("%s.%d.what" % (prefix, n), " " * p.depth + p.what) hdf.setValue("%s.%d.where" % (prefix, n), neo_cgi.htmlEscape(p.where)) class Profiler: def __init__ (self, klass, what): global PROFILER_START global PROFILER_ENABLED global PROFILER_DATA global PROFILER_DEPTH if not PROFILER_ENABLED: return self.when = time.time() - PROFILER_START self.klass = klass self.where = who_calls.pretty_who_calls() self.what = what self.length = 0 self.depth = PROFILER_DEPTH PROFILER_DEPTH = PROFILER_DEPTH + 1 PROFILER_DATA.append(self) def end(self): global PROFILER_ENABLED global PROFILER_DEPTH if not PROFILER_ENABLED: return self.length = time.time() - self.when - PROFILER_START PROFILER_DEPTH = PROFILER_DEPTH - 1 if PROFILER_DEPTH < 0: PROFILER_DEPTH = 0 class ProfilerCursor: def __init__ (self, real_cursor): self.real_cursor = real_cursor def execute (self, query, args=None): p = Profiler("SQL", query) r = self.real_cursor.execute(query, args) p.end() return r def __getattr__ (self, key): return getattr(self.real_cursor, key) clearsilver-0.10.5/python/examples/base/sgmllib.py0000755001211700116100000004564110261037514017114 00000000000000# A parser for SGML, using the derived class as static DTD. # XXX This only supports those SGML features used by HTML. # XXX There should be a way to distinguish between PCDATA (parsed # character data -- the normal case), RCDATA (replaceable character # data -- only char and entity references and end tags are special) # and CDATA (character data -- only end tags are special). # sgmlop support added by fredrik@pythonware.com (April 6, 1998) import re import string import sys try: from xml.parsers import sgmlop except ImportError: sgmlop = None # standard entity defs ENTITYDEFS = { 'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\'' } # SGML parser base class -- find tags and call handler functions. # Usage: p = SGMLParser(); p.feed(data); ...; p.close(). # The dtd is defined by deriving a class which defines methods # with special names to handle tags: start_foo and end_foo to handle # and , respectively, or do_foo to handle by itself. # (Tags are converted to lower case for this purpose.) The data # between tags is passed to the parser by calling self.handle_data() # with some data as argument (the data may be split up in arbutrary # chunks). Entity references are passed by calling # self.handle_entityref() with the entity reference as argument. # -------------------------------------------------------------------- # original re-based SGML parser interesting = re.compile('[&<]') incomplete = re.compile('&([a-zA-Z][a-zA-Z0-9]*|#[0-9]*)?|' '<([a-zA-Z][^<>]*|' '/([a-zA-Z][^<>]*)?|' '![^<>]*)?') entityref = re.compile('&([a-zA-Z][a-zA-Z0-9]*)[^a-zA-Z0-9]') charref = re.compile('&#([0-9]+)[^0-9]') starttagopen = re.compile('<[>a-zA-Z]') shorttagopen = re.compile('<[a-zA-Z][a-zA-Z0-9]*/') shorttag = re.compile('<([a-zA-Z][a-zA-Z0-9]*)/([^/]*)/') endtagopen = re.compile('a-zA-Z]') endbracket = re.compile('[<>]') special = re.compile(']*>') commentopen = re.compile('' _CS_TAG_RE = None _CS_TAG_REGEX = '<\\?.+?\\?>' def __init__ (self): self.tdb = db_trans.trans_connect() # configuration data ...... # - we should stop hardcoding this... - jeske self.root = "testroot" self.languages = ['es', 'en'] self.ignore_paths = ['tmpl/m'] # common place for mockups self.ignore_files = ['blah_ignore.cs'] # ignore clearsilver file # ignore clearsilver javascript files self.ignore_patterns = ['tmpl/[^ ]*_js.cs'] # ............................ if self.root is None: raise "Unable to determine installation root" if Translator._HTML_TAG_RE is None: Translator._HTML_TAG_RE = re.compile(Translator._HTML_TAG_REGEX, re.MULTILINE | re.DOTALL) if Translator._HTML_CMT_RE is None: Translator._HTML_CMT_RE = re.compile(Translator._HTML_CMT_REGEX, re.MULTILINE | re.DOTALL) if Translator._CS_TAG_RE is None: Translator._CS_TAG_RE = re.compile(Translator._CS_TAG_REGEX, re.MULTILINE | re.DOTALL) self._html_state = 0 def parseHTMLTag(self, data): # this is only called if we see a full tag in one parse... i = 0 if len(data) == 0: return [] if data[0] in '/?': return [] while i < len(data) and data[i] not in ' \n\r\t>': i = i + 1 if i == len(data): return [] tag = data[:i].lower() #print "Searching tag: %s" % data #print "Found tag: %s" % tag results = [] attrfind = re.compile( r'\s*([a-zA-Z_][-.a-zA-Z_0-9]*)(\s*=\s*' r'(\'[^\']*\'|"[^"]*"|[^ \t\n<>]*))?') k = i attrs = {} attrs_beg = {} while k < len(data): match = attrfind.match(data, k) if not match: break attrname, rest, attrvalue = match.group(1, 2, 3) if not rest: attrvalue = attrname elif attrvalue[:1] == '\'' == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] attrname = attrname.lower() if attrs.has_key(attrname): log("Can't handle duplicate attrs: %s" % attrname) attrs[attrname] = attrvalue attrs_beg[attrname] = match.start(3) k = match.end(0) find_l = [] if tag == "input": if attrs.get('type', "").lower() in ["submit", "button"]: find_l.append((attrs.get('value', ''), attrs_beg.get('value', 0))) for s,k in find_l: if s: x = data[k:].find(s) if x != -1: results.append((s, x+k, 1)) return results def parseHTML(self, data, reset=1): if reset: self._html_state = 0 if DEBUG: print "- %d ---------\n%s\n- E ---------" % (self._html_state, data) results = [] i = 0 n = len(data) # if we had state from the last parse... find it if self._html_state: if self._html_state == 2: x = string.find(data[i:], '-->') l = 3 else: x = string.find(data[i:], '>') l = 1 if x == -1: return results i = i + x + l self._html_state = 0 while i < n: if DEBUG: print "MATCHING>%s') tag_b = string.find(data[i:], '<') tag_e = string.find(data[i:], '>') if DEBUG: print "B> %d %d %d %d x and data[y] in string.whitespace: y-=1 results.append((data[x:y+1], x, 1)) if cmt_e == -1: # partial comment: self._html_state = 2 break i = i + cmt_e + 3 elif tag_b != -1: x = i y = i+tag_b-1 while x < y and data[x] in string.whitespace: x+=1 while y > x and data[y] in string.whitespace: y-=1 results.append((data[x:y+1], x, 1)) if tag_e == -1: # partial tag self._html_state = 1 break h_results = self.parseHTMLTag(data[i+tag_b+1:i+tag_e]) h_results = map(lambda x: (x[0], x[1] + i+tag_b+1, x[2]), h_results) results = results + h_results i = i + tag_e + 1 else: x = i y = n-1 while x < y and data[x] in string.whitespace: x+=1 while y > x and data[y] in string.whitespace: y-=1 results.append((data[x:y+1], x, 1)) break return results def parseCS(self, data): results = [] i = 0 n = len(data) while i < n: m = Translator._CS_TAG_RE.search(data, i) if not m: # search for a partial... x = string.find(data[i:], '') s = string.replace(s, '&', '&') for x in range (len (s)): n = ord(s[x]) if (n>47 and n<58) or (n>64 and n<91) or (n>96 and n<123): return 1 return 0 def findString(self, s): rows = self.tdb.strings.fetchRows( ('string', s) ) if len(rows) == 0: row = self.tdb.strings.newRow() row.string = s row.save() return row.string_id elif len(rows) > 1: raise eTransError, "String %s exists multiple times!" % s else: return rows[0].string_id def loadStrings(self, one_file=None, verbose=0): if one_file is not None: strings = self.handleFile(one_file) results = [(one_file, strings)] else: results = self.walkDirectory('tmpl') uniq = {} cnt = 0 seen_hdf = {} for fname, strings in results: for (s, ofs, ishtml) in strings: if s and string.strip(s): l = len(s) if ishtml: s = self.cleanHtmlString(s) if self.containsWords(s, ishtml): if type(ofs) == type(""): # HDF if seen_hdf.has_key(ofs): if seen_hdf[ofs][0] != s: log("Duplicate HDF Name %s:\n\t file %s = %s\n\t file %s = %s" % (ofs, seen_hdf[ofs][1], seen_hdf[ofs][0], fname, s)) else: seen_hdf[ofs] = (s, fname) try: uniq[s].append((fname, ofs, l)) except KeyError: uniq[s] = [(fname, ofs, l)] cnt = cnt + 1 print "%d strings, %d unique" % (cnt, len(uniq.keys())) fp = open("map", 'w') for (s, locs) in uniq.items(): locs = map(lambda x: "%s:%s:%d" % x, locs) fp.write('#: %s\n' % (string.join(locs, ','))) fp.write('msgid=%s\n\n' % repr(s)) log("Loading strings/locations into database") locations = [] for (s, locs) in uniq.items(): s_id = self.findString(s) for (fname, ofs, l) in locs: if type(ofs) == type(""): # ie, its HDF location = "hdf:%s" % ofs else: location = "ofs:%d:%d" % (ofs, l) loc_r = TransLoc(s_id, fname, location) locations.append(loc_r) return locations def stringsHDF(self, prefix, locations, lang='en', exist=0, tiered=0): hdf = neo_util.HDF() if exist and lang == 'en': return hdf done = {} locations.sort() maps = self.tdb.maps.fetchRows( ('lang', lang) ) maps_d = {} for map in maps: maps_d[int(map.string_id)] = map strings = self.tdb.strings.fetchRows() strings_d = {} for string in strings: strings_d[int(string.string_id)] = string count = 0 for loc in locations: s_id = int(loc.string_id) if done.has_key(s_id): continue try: s_row = maps_d[s_id] if exist: continue except KeyError: try: s_row = strings_d[s_id] except KeyError: log("Missing string_id %d, skipping" % s_id) continue count = count + 1 if tiered: hdf.setValue("%s.%d.%d.%s" % (prefix, int(s_id) / TIER1_DIV, int(s_id) / TIER2_DIV, s_id), s_row.string) else: hdf.setValue("%s.%s" % (prefix, s_id), s_row.string) done[s_id] = 1 if exist == 1: log("Missing %d strings for lang %s" % (count, lang)) return hdf def dumpStrings(self, locations, lang=None): log("Dumping strings to HDF") if lang is None: langs = ['en'] sql = "select lang from nt_trans_maps group by lang" cursor = self.tdb.defaultCursor() cursor.execute(sql) rows = cursor.fetchall() for row in rows: langs.append(row[0]) else: langs = [lang] for a_lang in langs: hdf = self.stringsHDF('S', locations, a_lang) hdf.writeFile("strings_%s.hdf" % a_lang) for a_lang in langs: hdf = self.stringsHDF('S', locations, a_lang, exist=1) if hdf.child(): hdf.writeFile("strings_missing_%s.hdf" % a_lang) def fetchString(self, s_id, lang): if lang == "hdf": return "" % (int(s_id) / TIER1_DIV, int(s_id) / TIER2_DIV, s_id) rows = self.tdb.maps.fetchRows( [('string_id', s_id), ('lang', lang)] ) if len(rows) == 0: try: row = self.tdb.strings.fetchRow( ('string_id', s_id) ) except odb.eNoMatchingRows: log("Unable to find string id %s" % s_id) raise eNoString if lang != 'en': log("Untranslated string for id %s" % s_id) return row.string else: return rows[0].string def dumpFiles(self, locations, lang): log("Dumping files for %s" % lang) files = {} for row in locations: try: files[row.filename].append(row) except KeyError: files[row.filename] = [row] hdf_map = [] os.system("rm -rf %s/gen/tmpl" % (self.root)) for file in files.keys(): fname = "%s/gen/%s" % (self.root, file) try: os.makedirs(os.path.dirname(fname)) except OSError, reason: if reason[0] != 17: raise do_hdf = 0 x = string.rfind(file, '.') if x != -1 and file[x:] == '.hdf': do_hdf = 1 ofs = [] for loc in files[file]: parts = string.split(loc.location, ':') if len(parts) == 3 and parts[0] == 'ofs' and do_hdf == 0: ofs.append((int(parts[1]), int(parts[2]), loc.string_id)) elif len(parts) == 2 and parts[0] == 'hdf' and do_hdf == 1: hdf_map.append((parts[1], loc.string_id)) else: log("Invalid location for loc_id %s" % loc.loc_id) continue if not do_hdf: ofs.sort() data = open(self.root + '/' + file).read() # ok, now we split up the original data into sections x = 0 n = len(data) out = [] #sys.stderr.write("%s\n" % repr(ofs)) while len(ofs): if ofs[0][0] > x: out.append(data[x:ofs[0][0]]) x = ofs[0][0] elif ofs[0][0] == x: out.append(self.fetchString(ofs[0][2], lang)) x = ofs[0][0] + ofs[0][1] ofs = ofs[1:] else: log("How did we get here? %s x=%d ofs=%d sid=%d" % (file, x, ofs[0][0], ofs[0][2])) log("Data[x:20]: %s" % data[x:20]) log("Data[ofs:20]: %s" % data[ofs[0][0]:20]) break if n > x: out.append(data[x:]) odata = string.join(out, '') open(fname, 'w').write(odata) if lang == "hdf": langs = self.languages else: langs = [lang] for d_lang in langs: # dumping the extracted strings hdf = self.stringsHDF('Lang.Extracted', locations, d_lang, tiered=1) fname = "%s/gen/tmpl/lang_%s.hdf" % (self.root, d_lang) hdf.writeFile(fname) data = open(fname).read() fp = open(fname, 'w') fp.write('## AUTOMATICALLY GENERATED -- DO NOT EDIT\n\n') fp.write(data) fp.write('\n#include "lang_map.hdf"\n') # dumping the hdf strings file if d_lang == "en": map_file = "%s/gen/tmpl/lang_map.hdf" % (self.root) else: map_file = "%s/gen/tmpl/%s/lang_map.hdf" % (self.root, d_lang) try: os.makedirs(os.path.dirname(map_file)) except OSError, reason: if reason[0] != 17: raise map_hdf = neo_util.HDF() for (name, s_id) in hdf_map: str = hdf.getValue('Lang.Extracted.%d.%d.%s' % (int(s_id) / TIER1_DIV, int(s_id) / TIER2_DIV, s_id), '') map_hdf.setValue(name, str) map_hdf.writeFile(map_file) def loadMap(self, file, prefix, lang): log("Loading map for language %s" % lang) hdf = neo_util.HDF() hdf.readFile(file) obj = hdf.getChild(prefix) updates = 0 new_r = 0 while obj is not None: s_id = obj.name() str = obj.value() try: map_r = self.tdb.maps.fetchRow( [('string_id', s_id), ('lang', lang)]) except odb.eNoMatchingRows: map_r = self.tdb.maps.newRow() map_r.string_id = s_id map_r.lang = lang new_r = new_r + 1 if map_r.string != str: updates = updates + 1 map_r.string = str map_r.save() obj = obj.next() log("New maps: %d Updates: %d" % (new_r, updates - new_r)) def main(argv): alist, args = getopt.getopt(argv[1:], "f:v:", ["help", "load=", "lang="]) one_file = None verbose = 0 load_file = None lang = 'en' for (field, val) in alist: if field == "--help": usage(argv[0]) return -1 if field == "-f": one_file = val if field == "-v": verbose = int(val) if field == "--load": load_file = val if field == "--lang": lang = val global DONE #signal.signal(signal.SIGTERM, handleSignal) #signal.signal(signal.SIGINT, handleSignal) log("trans: start") start_time = time.time() try: t = Translator() if load_file: t.loadMap(load_file, 'S', lang) else: locations = t.loadStrings(one_file, verbose=verbose) t.dumpStrings(locations) t.dumpFiles(locations, 'hdf') except KeyboardInterrupt: pass except: import handle_error handle_error.handleException("Translation Error") if __name__ == "__main__": main(sys.argv) clearsilver-0.10.5/python/examples/trans/trans.sql0000644001211700116100000000105410261037514017161 00000000000000create table nt_trans_strings ( string_id integer not null primary key auto_increment, string text, index(string(150)) ); create table nt_trans_locs ( loc_id integer not null primary key auto_increment, string_id integer not null, version integer default 0, filename varchar(255), location varchar(255), index(string_id), index(filename) ) TYPE=INNODB; create table nt_trans_maps ( map_id integer not null primary key auto_increment, string_id integer not null, lang char(2), string text, index(string_id) ) TYPE=INNODB; clearsilver-0.10.5/python/examples/trans/tstart.py0000755001211700116100000000043610261037514017212 00000000000000# this starts up the T-environment... # # The root dir should point to the top of the python tree import sys sys.path.insert(0, "../base") # pickup base libs sys.path.insert(0, "../../") # pickup neo_cgi.so # don't put anything above this because the path isn't # extended yet... clearsilver-0.10.5/python/neo_cgi.c0000644001211700116100000005344710645315377014144 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include #include "ClearSilver.h" #define NEO_CGI_MODULE #include "p_neo_util.h" static PyObject *CGIFinishedException; #define CGIObjectCheck(a) (!(strcmp((a)->ob_type->tp_name, CGIObjectType.tp_name))) typedef struct _CGIObject { PyObject_HEAD CGI *cgi; PyObject *hdf; PyObject *upload_cb; PyObject *upload_rock; int upload_error; } CGIObject; static PyObject *p_cgi_value_get_attr (CGIObject *self, char *name); static void p_cgi_dealloc (CGIObject *ho); PyTypeObject CGIObjectType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "CGIObjectType", /*tp_name*/ sizeof(CGIObject), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ (destructor)p_cgi_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)p_cgi_value_get_attr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)0, /*tp_repr*/ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_as_hash */ }; static void p_cgi_dealloc (CGIObject *ho) { if (ho->cgi) { cgi_destroy (&(ho->cgi)); } PyObject_DEL(ho); } PyObject * p_cgi_to_object (CGI *data) { PyObject *rv; if (data == NULL) { rv = Py_None; Py_INCREF (rv); } else { CGIObject *ho = PyObject_NEW (CGIObject, &CGIObjectType); if (ho == NULL) return NULL; ho->cgi = data; ho->hdf = p_hdf_to_object (data->hdf, 0); Py_INCREF(ho->hdf); rv = (PyObject *) ho; } return rv; } static PyObject * p_cgi_init (PyObject *self, PyObject *args) { CGI *cgi = NULL; NEOERR *err; err = cgi_init (&cgi, NULL); if (err) return p_neo_error (err); return p_cgi_to_object (cgi); } static PyObject * p_cgi_parse (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; CGIObject *p_cgi = (CGIObject *) self; PyObject *rv; NEOERR *err; p_cgi->upload_error = 0; err = cgi_parse (cgi); if (err) return p_neo_error (err); if (p_cgi->upload_error) { p_cgi->upload_error = 0; return NULL; } rv = Py_None; Py_INCREF(rv); return rv; } static int python_upload_cb (CGI *cgi, int nread, int expected) { CGIObject *self = (CGIObject *)(cgi->data); PyObject *cb, *rock; PyObject *args, *result; int r; /* fprintf(stderr, "upload_cb: %d/%d\n", nread, expected); */ cb = self->upload_cb; rock = self->upload_rock; if (cb == NULL) return 0; args = Py_BuildValue("(Oii)", rock, nread, expected); if (args == NULL) { self->upload_error = 1; return 1; } result = PyEval_CallObject(cb, args); Py_DECREF(args); if (result != NULL && !PyInt_Check(result)) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_TypeError, "upload_cb () returned non-integer"); self->upload_error = 1; return 1; } r = PyInt_AsLong(result); Py_DECREF(result); result = NULL; return r; } static PyObject * p_cgi_set_upload_cb (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; CGIObject *p_cgi = (CGIObject *) self; PyObject *rock, *cb; if (!PyArg_ParseTuple(args, "OO:setUploadCB(rock, func)", &rock, &cb)) return NULL; cgi->data = self; cgi->upload_cb = python_upload_cb; p_cgi->upload_cb = cb; p_cgi->upload_rock = rock; p_cgi->upload_error = 0; Py_INCREF(cb); Py_INCREF(rock); Py_INCREF(Py_None); return Py_None; } static PyObject * p_cgi_error (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *s; PyObject *rv; if (!PyArg_ParseTuple(args, "s:error(str)", &s)) return NULL; cgi_error (cgi, s); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_cgi_display (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *file; PyObject *rv; NEOERR *err; if (!PyArg_ParseTuple(args, "s:display(file)", &file)) return NULL; err = cgi_display (cgi, file); if (err) return p_neo_error (err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_cgi_redirect (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *s; PyObject *rv; if (!PyArg_ParseTuple(args, "s:redirect(str)", &s)) return NULL; cgi_redirect (cgi, "%s", s); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_cgi_redirect_uri (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *s; PyObject *rv; if (!PyArg_ParseTuple(args, "s:redirectUri(str)", &s)) return NULL; cgi_redirect_uri (cgi, "%s", s); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_cgi_cookie_authority (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *s, *host; PyObject *rv; if (!PyArg_ParseTuple(args, "s:cookieAuthority(host)", &host)) return NULL; s = cgi_cookie_authority (cgi, host); if (s == NULL) { rv = Py_None; Py_INCREF(rv); } else { rv = Py_BuildValue ("s", s); } return rv; } static PyObject * p_cgi_cookie_set (PyObject *self, PyObject *args, PyObject *keywds) { CGI *cgi = ((CGIObject *) self)->cgi; char *name, *value, *path = NULL, *domain = NULL, *time_str = NULL; int persist = 0; int secure = 0; NEOERR *err; static char *kwlist[] = {"name", "value", "path", "domain", "time_str", "persist", "secure", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "ss|sssii:cookieSet()", kwlist, &name, &value, &path, &domain, &time_str, &persist, &secure)) return NULL; err = cgi_cookie_set (cgi, name, value, path, domain, time_str, persist, secure); if (err) return p_neo_error (err); Py_INCREF(Py_None); return Py_None; } static PyObject * p_cgi_cookie_clear (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *name, *domain = NULL, *path = NULL; NEOERR *err; if (!PyArg_ParseTuple(args, "s|ss:cookieClear(name, domain, path)", &name, &domain, &path)) return NULL; err = cgi_cookie_clear (cgi, name, domain, path); if (err) return p_neo_error (err); Py_INCREF(Py_None); return Py_None; } static PyObject * p_cgi_filehandle (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; char *name; FILE *fp; if (!PyArg_ParseTuple(args, "s:filehandle(form_name)", &name)) return NULL; fp = cgi_filehandle (cgi, name); if (fp == NULL) { Py_INCREF(Py_None); return Py_None; } return PyFile_FromFile (fp, name, "w+", NULL); } static PyObject * p_cgi_cs_init (PyObject *self, PyObject *args) { CGI *cgi = ((CGIObject *) self)->cgi; NEOERR *err; CSPARSE *cs; if (!PyArg_ParseTuple(args, ":cs()")) return NULL; err = cgi_cs_init(cgi, &cs); if (err) return p_neo_error (err); return p_cs_to_object(cs); } static PyMethodDef CGIMethods[] = { #if 0 {"debugInit", p_cgi_debug_init, METH_VARARGS, NULL}, {"wrapInit", p_cgi_wrap_init, METH_VARARGS, NULL}, #endif {"parse", p_cgi_parse, METH_VARARGS, NULL}, {"setUploadCB", p_cgi_set_upload_cb, METH_VARARGS, NULL}, {"error", p_cgi_error, METH_VARARGS, NULL}, {"display", p_cgi_display, METH_VARARGS, NULL}, {"redirect", p_cgi_redirect, METH_VARARGS, NULL}, {"redirectUri", p_cgi_redirect_uri, METH_VARARGS, NULL}, {"cookieAuthority", p_cgi_cookie_authority, METH_VARARGS, NULL}, {"cookieSet", (PyCFunction)p_cgi_cookie_set, METH_VARARGS|METH_KEYWORDS, NULL}, {"cookieClear", p_cgi_cookie_clear, METH_VARARGS, NULL}, {"filehandle", p_cgi_filehandle, METH_VARARGS, NULL}, {"cs", p_cgi_cs_init, METH_VARARGS, NULL}, {NULL, NULL} }; static PyObject * p_cgi_url_escape (PyObject *self, PyObject *args) { char *s, *esc, *o = NULL; NEOERR *err; PyObject *rv; if (!PyArg_ParseTuple(args, "s|s:urlEscape(str, other=None)", &s, &o)) return NULL; err = cgi_url_escape_more (s, &esc, o); if (err) return p_neo_error (err); rv = Py_BuildValue ("s", esc); free (esc); return rv; } static PyObject * p_cgi_url_unescape (PyObject *self, PyObject *args) { char *s; PyObject *rv; char *r; if (!PyArg_ParseTuple(args, "s:urlUnescape(str)", &s)) return NULL; r = strdup(s); if (r == NULL) return PyErr_NoMemory(); cgi_url_unescape (r); rv = Py_BuildValue ("s", r); free (r); return rv; } static PyObject * p_html_escape (PyObject *self, PyObject *args) { char *s, *esc; NEOERR *err; PyObject *rv; int len; if (!PyArg_ParseTuple(args, "s#:htmlEscape(str)", &s, &len)) return NULL; err = html_escape_alloc (s, len, &esc); if (err) return p_neo_error (err); rv = Py_BuildValue ("s", esc); free (esc); return rv; } static PyObject * p_html_strip (PyObject *self, PyObject *args) { char *s, *esc; NEOERR *err; PyObject *rv; int len; if (!PyArg_ParseTuple(args, "s#:htmlStrip(str)", &s, &len)) return NULL; err = html_strip_alloc (s, len, &esc); if (err) return p_neo_error (err); rv = Py_BuildValue ("s", esc); free (esc); return rv; } static PyObject * p_text_html (PyObject *self, PyObject *args, PyObject *keywds) { char *s, *esc; NEOERR *err; PyObject *rv; int len; HTML_CONVERT_OPTS opts; static char *kwlist[] = {"text", "bounce_url", "url_class", "url_target", "mailto_class", "long_lines", "space_convert", "newlines_convert", "longline_width", "check_ascii_art", "link_name", NULL}; /* These defaults all come from the old version */ opts.bounce_url = NULL; opts.url_class = NULL; opts.url_target = "_blank"; opts.mailto_class = NULL; opts.long_lines = 0; opts.space_convert = 0; opts.newlines_convert = 1; opts.longline_width = 75; /* This hasn't been used in a while, actually */ opts.check_ascii_art = 1; opts.link_name = NULL; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s#|ssssiiiiis:text2html(text)", kwlist, &s, &len, &(opts.bounce_url), &(opts.url_class), &(opts.url_target), &(opts.mailto_class), &(opts.long_lines), &(opts.space_convert), &(opts.newlines_convert), &(opts.longline_width), &(opts.check_ascii_art), &(opts.link_name))) return NULL; err = convert_text_html_alloc_options (s, len, &esc, &opts); if (err) return p_neo_error (err); rv = Py_BuildValue ("s", esc); free (esc); return rv; } PyObject *p_cgi_value_get_attr (CGIObject *ho, char *name) { if (!strcmp(name, "hdf")) { Py_INCREF(ho->hdf); return ho->hdf; } return Py_FindMethod(CGIMethods, (PyObject *)ho, name); } /* Enable wrapping of newlib stdin/stdout output to go through python */ typedef struct wrapper_data { PyObject *p_stdin; PyObject *p_stdout; PyObject *p_env; } WRAPPER_DATA; static WRAPPER_DATA Wrapper = {NULL, NULL, NULL}; static char cgiwrap_doc[] = "cgiwrap(stdin, stdout, env)\nMethod that will cause all cgiwrapped stdin/stdout functions to be redirected to the python stdin/stdout file objects specified. Also redirect getenv/putenv calls (env should be either a python dictionary or os.environ)"; static PyObject * cgiwrap (PyObject *self, PyObject *args) { PyObject *p_stdin; PyObject *p_stdout; PyObject *p_env; if (!PyArg_ParseTuple(args, "OOO:cgiwrap(stdin, stdout, env)", &p_stdin, &p_stdout, &p_env)) return NULL; if (p_stdin != Py_None) { if (Wrapper.p_stdin != NULL) { Py_DECREF (Wrapper.p_stdin); } Wrapper.p_stdin = p_stdin; Py_INCREF (Wrapper.p_stdin); } if (p_stdout != Py_None) { if (Wrapper.p_stdout != NULL) { Py_DECREF (Wrapper.p_stdout); } Wrapper.p_stdout = p_stdout; Py_INCREF (Wrapper.p_stdout); } if (p_env != Py_None) { if (Wrapper.p_env != NULL) { Py_DECREF (Wrapper.p_env); } Wrapper.p_env = p_env; Py_INCREF (Wrapper.p_env); } Py_INCREF(Py_None); return Py_None; } static int p_writef (void *data, const char *fmt, va_list ap) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; PyObject *str; char *buf; int len; int err; buf = vsprintf_alloc(fmt, ap); len = visprintf_alloc(&buf, fmt, ap); if (buf == NULL) return 0; str = PyString_FromStringAndSize (buf, len); free(buf); err = PyFile_WriteObject(str, wrap->p_stdout, Py_PRINT_RAW); Py_DECREF(str); if (err == 0) { PyErr_Clear(); return len; } PyErr_Clear(); return err; } static int p_write (void *data, const char *buf, int len) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; PyObject *s; int err; s = PyString_FromStringAndSize (buf, len); err = PyFile_WriteObject(s, wrap->p_stdout, Py_PRINT_RAW); Py_DECREF(s); if (err == 0) { PyErr_Clear(); return len; } PyErr_Clear(); return err; } /* Similar to the PyFile_GetLine function, this one invokes read on the * file object */ static PyObject *PyFile_Read (PyObject *f, int n) { if (f == NULL) { PyErr_BadInternalCall(); return NULL; } /* If this was in the python fileobject code, we could handle this * directly for builtin file objects. Oh well. */ /* if (!PyFile_Check(f))*/ else { PyObject *reader; PyObject *args; PyObject *result; reader = PyObject_GetAttrString(f, "read"); if (reader == NULL) return NULL; if (n <= 0) args = Py_BuildValue("()"); else args = Py_BuildValue("(i)", n); if (args == NULL) { Py_DECREF(reader); return NULL; } result = PyEval_CallObject(reader, args); Py_DECREF(reader); Py_DECREF(args); if (result != NULL && !PyString_Check(result)) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_TypeError, "object.read() returned non-string"); } return result; } } static int p_read (void *data, char *ptr, int len) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; PyObject *buf; char *s; buf = PyFile_Read (wrap->p_stdin, len); if (buf == NULL) { PyErr_Clear(); return -1; } len = PyString_Size(buf); s = PyString_AsString(buf); memcpy (ptr, s, len); Py_DECREF(buf); PyErr_Clear(); return len; } /* We can't really have an error return from this (and the other * cgiwrap) function, because the API doesn't have an error return, * and if we get back to python, the error will occur at the next random * place that python actually checks for errors independent of an error * return. Not the best way to do things, but its what we've got. Some * of these we can check for in cgiWrap() */ static char *p_getenv (void *data, const char *s) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; PyObject *get; PyObject *args = NULL; PyObject *result; char *ret = NULL; get = PyObject_GetAttrString(wrap->p_env, "__getitem__"); if (get != NULL) { args = Py_BuildValue("(s)", s); if (args == NULL) { Py_DECREF(get); PyErr_Clear(); return NULL; } } else { /* Python 1.5.2 and earlier don't have __getitem__ on the standard * dict object, so we'll just use get for them */ get = PyObject_GetAttrString(wrap->p_env, "get"); if (get != NULL) { args = Py_BuildValue("(s,O)", s, Py_None); if (args == NULL) { Py_DECREF(get); PyErr_Clear(); return NULL; } } } if (get == NULL) { ne_warn("Unable to get __getitem__ from env"); PyErr_Clear(); return NULL; } result = PyEval_CallObject(get, args); Py_DECREF(get); Py_DECREF(args); if (result != NULL && !PyString_Check(result) && (result != Py_None)) { Py_DECREF(result); result = NULL; PyErr_SetString(PyExc_TypeError, "env.get() returned non-string"); } if (result != NULL && result != Py_None) { ret = strdup (PyString_AsString(result)); Py_DECREF (result); } PyErr_Clear(); return ret; } static int p_iterenv (void *data, int x, char **rk, char **rv) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; PyObject *items; PyObject *env_list; PyObject *result; PyObject *k, *v; items = PyObject_GetAttrString(wrap->p_env, "items"); if (items == NULL) { ne_warn ("p_iterenv: Unable to get items method"); PyErr_Clear(); return -1; } env_list = PyEval_CallObject(items, NULL); Py_DECREF(items); if (env_list == NULL) { ne_warn ("p_iterenv: Unable to call items method"); PyErr_Clear(); return -1; } if (x >= PyList_Size(env_list)) { *rk = NULL; *rv = NULL; Py_DECREF(env_list); return 0; } result = PyList_GetItem (env_list, x); if (result == NULL) { ne_warn ("p_iterenv: Unable to get env %d", x); Py_DECREF(env_list); PyErr_Clear(); return -1; } k = PyTuple_GetItem (result, 0); v = PyTuple_GetItem (result, 1); if (k == NULL || v == NULL) { ne_warn ("p_iterenv: Unable to get k,v %p,%p", k, v); Py_DECREF(env_list); PyErr_Clear(); return -1; } *rk = strdup(PyString_AsString(k)); *rv = strdup(PyString_AsString(v)); if (*rk == NULL || *rv == NULL) { if (*rk) free (*rk); if (*rv) free (*rv); Py_DECREF(env_list); PyErr_Clear(); return -1; } Py_DECREF(env_list); PyErr_Clear(); return 0; } static int p_putenv (void *data, const char *k, const char *v) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; PyObject *set; PyObject *args; PyObject *result; if (k == NULL || v == NULL) return -1; set = PyObject_GetAttrString(wrap->p_env, "__setitem__"); if (set == NULL) { PyErr_Clear(); return -1; } args = Py_BuildValue("(s,s)", k, v); if (args == NULL) { Py_DECREF(set); PyErr_Clear(); return -1; } result = PyEval_CallObject(set, args); Py_DECREF(set); Py_DECREF(args); if (result == NULL) { PyErr_Clear(); return -1; } Py_DECREF(result); PyErr_Clear(); return 0; } static void p_cgiwrap_init(PyObject *m) { PyObject *sys, *os, *p_stdin, *p_stdout, *args, *p_env; #if 0 PyObject *argv; int x; #endif /* Set up the python wrapper * This might not be enough to actually continue to point to * sys.stdin/sys.stdout, we'd probably have to actually do the lookup * every time... if we need that functionality */ sys = PyImport_ImportModule("sys"); os = PyImport_ImportModule("os"); if (sys) { p_stdin = PyObject_GetAttrString(sys, "stdin"); p_stdout = PyObject_GetAttrString(sys, "stdout"); #if 0 argv = PyObject_GetAttrString(sys, "argv"); if (argv) { Argc = PyList_Size (argv); if (Argc != -1) { Argv = (char **) malloc (sizeof (char *) * (Argc+1)); for (x = 0; x < Argc; x++) { PyObject *a; char *b; a = PyList_GetItem (argv, x); if (a == NULL) break; b = PyString_AsString(a); if (b == NULL) break; Argv[x] = b; } Argv[x] = NULL; } } #endif if (os) { p_env = PyObject_GetAttrString(os, "environ"); } else { Py_INCREF(Py_None); p_env = Py_None; } args = Py_BuildValue("(O,O,O)", p_stdin, p_stdout, p_env); if (args) { cgiwrap_init_emu (&Wrapper, p_read, p_writef, p_write, p_getenv, p_putenv, p_iterenv); cgiwrap (m, args); Py_DECREF(args); } } } static PyObject * p_ignore (PyObject *self, PyObject *args) { int i = 0; if (!PyArg_ParseTuple(args, "i:IgnoreEmptyFormVars(bool)", &i)) return NULL; IgnoreEmptyFormVars = i; Py_INCREF(Py_None); return Py_None; } static PyObject * p_export_date (PyObject *self, PyObject *args) { NEOERR *err; PyObject *ho; int i = 0; char *prefix; char *timezone; HDF *hdf; if (!PyArg_ParseTuple(args, "Ossi:exportDate(hdf, prefix, timezone, time_t)", &ho, &prefix, &timezone, &i)) return NULL; hdf = p_object_to_hdf (ho); if (hdf == NULL) { PyErr_SetString(PyExc_TypeError, "First argument must be an HDF Object"); return NULL; } err = export_date_time_t (hdf, prefix, timezone, i); if (err) return p_neo_error (err); Py_INCREF(Py_None); return Py_None; } static PyObject * p_update (PyObject *self, PyObject *args) { if (_PyImport_FindExtension("neo_util","neo_util") == NULL) initneo_util(); if (_PyImport_FindExtension("neo_cs","neo_cs") == NULL) initneo_cs(); Py_INCREF(Py_None); return Py_None; } static PyMethodDef ModuleMethods[] = { {"CGI", p_cgi_init, METH_VARARGS, NULL}, {"urlEscape", p_cgi_url_escape, METH_VARARGS, NULL}, {"urlUnescape", p_cgi_url_unescape, METH_VARARGS, NULL}, {"htmlEscape", p_html_escape, METH_VARARGS, NULL}, {"htmlStrip", p_html_strip, METH_VARARGS, NULL}, {"text2html", (PyCFunction)p_text_html, METH_VARARGS|METH_KEYWORDS, NULL}, {"cgiWrap", cgiwrap, METH_VARARGS, cgiwrap_doc}, {"IgnoreEmptyFormVars", p_ignore, METH_VARARGS, NULL}, {"exportDate", p_export_date, METH_VARARGS, NULL}, {"update", p_update, METH_VARARGS, NULL}, {NULL, NULL} }; DL_EXPORT(void) initneo_cgi(void) { PyObject *m, *d; static void *NEO_PYTHON_API[P_NEO_CGI_POINTERS]; PyObject *c_api_object; CGIObjectType.ob_type = &PyType_Type; initneo_util(); _PyImport_FixupExtension("neo_util", "neo_util"); initneo_cs(); _PyImport_FixupExtension("neo_cs", "neo_cs"); m = Py_InitModule("neo_cgi", ModuleMethods); p_cgiwrap_init (m); d = PyModule_GetDict(m); CGIFinishedException = PyErr_NewException("neo_cgi.CGIFinished", NULL, NULL); PyDict_SetItemString(d, "CGIFinished", CGIFinishedException); /* Initialize the C API Pointer array */ NEO_PYTHON_API[P_HDF_TO_OBJECT_NUM] = (void *)p_hdf_to_object; NEO_PYTHON_API[P_OBJECT_TO_HDF_NUM] = (void *)p_object_to_hdf; NEO_PYTHON_API[P_NEO_ERROR_NUM] = (void *)p_neo_error; /* create a CObject containing the API pointer array's address */ c_api_object = PyCObject_FromVoidPtr((void *)NEO_PYTHON_API, NULL); if (c_api_object != NULL) { /* create a name for this object in the module's namespace */ PyDict_SetItemString(d, "_C_API", c_api_object); Py_DECREF(c_api_object); PyDict_SetItemString(d, "_C_API_NUM", PyInt_FromLong(P_NEO_CGI_POINTERS)); } } clearsilver-0.10.5/python/neo_cgi.def0000644001211700116100000000006010261037514014423 00000000000000 EXPORTS initneo_cgi initneo_util initneo_csclearsilver-0.10.5/python/neo_cs.c0000644001211700116100000000774610524726372014005 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include #include "ClearSilver.h" #define NEO_CGI_MODULE #include "p_neo_util.h" #define CSObjectCheck(a) (!(strcmp((a)->ob_type->tp_name, CSObjectType.tp_name))) typedef struct _CSObject { PyObject_HEAD CSPARSE *data; } CSObject; static PyObject *p_cs_value_get_attr (CSObject *self, char *name); static void p_cs_dealloc (CSObject *ho); static PyTypeObject CSObjectType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "CSObjectType", /*tp_name*/ sizeof(CSObject), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ (destructor)p_cs_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)p_cs_value_get_attr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)0, /*tp_repr*/ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_as_hash */ }; static void p_cs_dealloc (CSObject *ho) { /* ne_warn("deallocating hdf: %X", ho); */ if (ho->data) { cs_destroy (&(ho->data)); } PyObject_DEL(ho); } PyObject * p_cs_to_object (CSPARSE *data) { PyObject *rv; if (data == NULL) { rv = Py_None; Py_INCREF (rv); } else { CSObject *ho = PyObject_NEW (CSObject, &CSObjectType); if (ho == NULL) return NULL; ho->data = data; rv = (PyObject *) ho; /* ne_warn("allocating cs: %X", ho); */ } return rv; } static PyObject * p_cs_init (PyObject *self, PyObject *args) { CSPARSE *cs = NULL; NEOERR *err; PyObject *ho; HDF *hdf; if (!PyArg_ParseTuple(args, "O:CS(HDF Object)", &ho)) return NULL; hdf = p_object_to_hdf (ho); if (hdf == NULL) { PyErr_BadArgument(); return NULL; } err = cs_init (&cs, hdf); if (err) return p_neo_error (err); err = cgi_register_strfuncs(cs); if (err) return p_neo_error (err); return p_cs_to_object (cs); } static PyObject * p_cs_parse_file (PyObject *self, PyObject *args) { CSObject *co = (CSObject *)self; NEOERR *err; char *path; if (!PyArg_ParseTuple(args, "s:parseFile(path)", &path)) return NULL; err = cs_parse_file (co->data, path); if (err) return p_neo_error(err); Py_INCREF(Py_None); return Py_None; } static PyObject * p_cs_parse_str (PyObject *self, PyObject *args) { CSObject *co = (CSObject *)self; NEOERR *err; char *s, *ms; int l; if (!PyArg_ParseTuple(args, "s#:parseStr(string)", &s, &l)) return NULL; ms = strdup(s); if (ms == NULL) return PyErr_NoMemory(); err = cs_parse_string (co->data, ms, l); if (err) return p_neo_error(err); Py_INCREF(Py_None); return Py_None; } static NEOERR *render_cb (void *ctx, char *buf) { STRING *str= (STRING *)ctx; return nerr_pass(string_append(str, buf)); } static PyObject * p_cs_render (PyObject *self, PyObject *args) { CSObject *co = (CSObject *)self; NEOERR *err; STRING str; PyObject *rv; string_init(&str); err = cs_render (co->data, &str, render_cb); if (err) return p_neo_error(err); rv = Py_BuildValue ("s", str.buf); string_clear (&str); return rv; } static PyMethodDef CSMethods[] = { {"parseFile", p_cs_parse_file, METH_VARARGS, NULL}, {"parseStr", p_cs_parse_str, METH_VARARGS, NULL}, {"render", p_cs_render, METH_VARARGS, NULL}, {NULL, NULL} }; static PyMethodDef ModuleMethods[] = { {"CS", p_cs_init, METH_VARARGS, NULL}, {NULL, NULL} }; PyObject *p_cs_value_get_attr (CSObject *ho, char *name) { return Py_FindMethod(CSMethods, (PyObject *)ho, name); } DL_EXPORT(void) initneo_cs(void) { PyObject *m, *d; CSObjectType.ob_type = &PyType_Type; m = Py_InitModule("neo_cs", ModuleMethods); d = PyModule_GetDict(m); } clearsilver-0.10.5/python/neo_util.c0000644001211700116100000003640010524726422014336 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include #include "ClearSilver.h" #define NEO_CGI_MODULE #include "p_neo_util.h" static PyObject *NeoError; static PyObject *NeoParseError; PyObject * p_neo_error (NEOERR *err) { STRING str; string_init (&str); if (nerr_match(err, NERR_PARSE)) { nerr_error_string (err, &str); PyErr_SetString (NeoParseError, str.buf); } else { nerr_error_traceback (err, &str); PyErr_SetString (NeoError, str.buf); } string_clear (&str); return NULL; } #define HDFObjectCheck(a) (!(strcmp((a)->ob_type->tp_name, HDFObjectType.tp_name))) typedef struct _HDFObject { PyObject_HEAD HDF *data; int dealloc; } HDFObject; static PyObject *p_hdf_value_get_attr (HDFObject *self, char *name); static void p_hdf_dealloc (HDFObject *ho); static PyTypeObject HDFObjectType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "HDFObjectType", /*tp_name*/ sizeof(HDFObject), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ (destructor)p_hdf_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)p_hdf_value_get_attr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)0, /*tp_repr*/ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_as_hash */ }; static void p_hdf_dealloc (HDFObject *ho) { /* ne_warn("deallocating hdf: %X", ho); */ if (ho->data && ho->dealloc) { hdf_destroy (&(ho->data)); } PyObject_DEL(ho); } PyObject * p_hdf_to_object (HDF *data, int dealloc) { PyObject *rv; if (data == NULL) { rv = Py_None; Py_INCREF (rv); } else { HDFObject *ho = PyObject_NEW (HDFObject, &HDFObjectType); if (ho == NULL) return NULL; ho->data = data; ho->dealloc = dealloc; rv = (PyObject *) ho; /* ne_warn("allocating hdf: %X", ho); */ } return rv; } HDF * p_object_to_hdf (PyObject *ho) { if (HDFObjectCheck(ho)) { return ((HDFObject *)ho)->data; } return NULL; } static PyObject * p_hdf_init (PyObject *self, PyObject *args) { HDF *hdf = NULL; NEOERR *err; err = hdf_init (&hdf); if (err) return p_neo_error (err); return p_hdf_to_object (hdf, 1); } static PyObject * p_hdf_get_int_value (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name; int r, d = 0; if (!PyArg_ParseTuple(args, "si:getIntValue(name, default)", &name, &d)) return NULL; r = hdf_get_int_value (ho->data, name, d); rv = Py_BuildValue ("i", r); return rv; } static PyObject * p_hdf_get_value (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name; char *r, *d = NULL; if (!PyArg_ParseTuple(args, "ss:getValue(name, default)", &name, &d)) return NULL; r = hdf_get_value (ho->data, name, d); rv = Py_BuildValue ("s", r); return rv; } static PyObject * p_hdf_get_obj (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name; HDF *r; if (!PyArg_ParseTuple(args, "s:getObj(name)", &name)) return NULL; r = hdf_get_obj (ho->data, name); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = p_hdf_to_object (r, 0); return rv; } static PyObject * p_hdf_get_child (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name; HDF *r; if (!PyArg_ParseTuple(args, "s:getChild(name)", &name)) return NULL; r = hdf_get_child (ho->data, name); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = p_hdf_to_object (r, 0); return rv; } static PyObject * p_hdf_get_attr (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv, *item; char *name; HDF_ATTR *attr; if (!PyArg_ParseTuple(args, "s:getAttrs(name)", &name)) return NULL; rv = PyList_New(0); if (rv == NULL) return NULL; Py_INCREF(rv); attr = hdf_get_attr (ho->data, name); while (attr != NULL) { item = Py_BuildValue("(s,s)", attr->key, attr->value); if (item == NULL) { Py_DECREF(rv); return NULL; } if (PyList_Append(rv, item) == -1) { Py_DECREF(rv); return NULL; } attr = attr->next; } return rv; } static PyObject * p_hdf_obj_attr (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv, *item; HDF_ATTR *attr; rv = PyList_New(0); if (rv == NULL) return NULL; Py_INCREF(rv); attr = hdf_obj_attr (ho->data); while (attr != NULL) { item = Py_BuildValue("(s,s)", attr->key, attr->value); if (item == NULL) { Py_DECREF(rv); return NULL; } if (PyList_Append(rv, item) == -1) { Py_DECREF(rv); return NULL; } attr = attr->next; } return rv; } static PyObject * p_hdf_obj_child (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; HDF *r; r = hdf_obj_child (ho->data); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = p_hdf_to_object (r, 0); return rv; } static PyObject * p_hdf_obj_next (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; HDF *r; r = hdf_obj_next (ho->data); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = p_hdf_to_object (r, 0); return rv; } static PyObject * p_hdf_obj_top (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; HDF *r; r = hdf_obj_top (ho->data); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = p_hdf_to_object (r, 0); return rv; } static PyObject * p_hdf_obj_name (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *r; r = hdf_obj_name (ho->data); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = Py_BuildValue ("s", r); return rv; } static PyObject * p_hdf_obj_value (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *r; r = hdf_obj_value (ho->data); if (r == NULL) { rv = Py_None; Py_INCREF(rv); return rv; } rv = Py_BuildValue ("s", r); return rv; } static PyObject * p_hdf_set_value (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name, *value; NEOERR *err; int nlen = 0; int vlen = 0; if (!PyArg_ParseTuple(args, "s#s#:setValue(name, value)", &name, &nlen, &value, &vlen)) return NULL; err = hdf_set_value (ho->data, name, value); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_set_attr (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name, *value, *key; NEOERR *err; if (!PyArg_ParseTuple(args, "ssO:setAttr(name, key, value)", &name, &key, &rv)) return NULL; if (PyString_Check(rv)) { value = PyString_AsString(rv); } else if (rv == Py_None) { value = NULL; } else { return PyErr_Format(PyExc_TypeError, "Invalid type for value, expected None or string"); } err = hdf_set_attr (ho->data, name, key, value); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_read_file (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *path; NEOERR *err; if (!PyArg_ParseTuple(args, "s:readFile(path)", &path)) return NULL; err = hdf_read_file (ho->data, path); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_write_file (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *path; NEOERR *err; if (!PyArg_ParseTuple(args, "s:writeFile(path)", &path)) return NULL; err = hdf_write_file (ho->data, path); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_write_file_atomic (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *path; NEOERR *err; if (!PyArg_ParseTuple(args, "s:writeFile(path)", &path)) return NULL; err = hdf_write_file_atomic (ho->data, path); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_remove_tree (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *name; NEOERR *err; if (!PyArg_ParseTuple(args, "s:removeTree(name)", &name)) return NULL; err = hdf_remove_tree (ho->data, name); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_dump (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; NEOERR *err; STRING str; string_init (&str); err = hdf_dump_str (ho->data, NULL, 0, &str); if (err) return p_neo_error(err); rv = Py_BuildValue ("s", str.buf); string_clear (&str); return rv; } static PyObject * p_hdf_write_string (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; NEOERR *err; char *s = NULL; err = hdf_write_string (ho->data, &s); if (err) return p_neo_error(err); rv = Py_BuildValue ("s", s); if (s) free(s); return rv; } static PyObject * p_hdf_read_string (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; NEOERR *err; char *s = NULL; int ignore = 0; if (!PyArg_ParseTuple(args, "s|i:readString(string)", &s, &ignore)) return NULL; err = hdf_read_string_ignore (ho->data, s, ignore); if (err) return p_neo_error(err); Py_INCREF (Py_None); return Py_None; } static PyObject * p_hdf_copy (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; HDF *src = NULL; PyObject *rv, *o = NULL; char *name; NEOERR *err; if (!PyArg_ParseTuple(args, "sO:copy(name, src_hdf)", &name, &o)) return NULL; src = p_object_to_hdf (o); if (src == NULL) { PyErr_Format(PyExc_TypeError, "second argument must be an HDFObject"); return NULL; } err = hdf_copy (ho->data, name, src); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_set_symlink (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *src; char *dest; NEOERR *err; if (!PyArg_ParseTuple(args, "ss:setSymLink(src, dest)", &src, &dest)) return NULL; err = hdf_set_symlink (ho->data, src, dest); if (err) return p_neo_error(err); rv = Py_None; Py_INCREF(rv); return rv; } static PyObject * p_hdf_search_path (PyObject *self, PyObject *args) { HDFObject *ho = (HDFObject *)self; PyObject *rv; char *path; char full[_POSIX_PATH_MAX]; NEOERR *err; if (!PyArg_ParseTuple(args, "s:searchPath(path)", &path)) return NULL; err = hdf_search_path (ho->data, path, full); if (err) return p_neo_error(err); rv = PyString_FromString(full); return rv; } static PyMethodDef HDFMethods[] = { {"getIntValue", p_hdf_get_int_value, METH_VARARGS, NULL}, {"getValue", p_hdf_get_value, METH_VARARGS, NULL}, {"getObj", p_hdf_get_obj, METH_VARARGS, NULL}, {"getChild", p_hdf_get_child, METH_VARARGS, NULL}, {"getAttrs", p_hdf_get_attr, METH_VARARGS, NULL}, {"child", p_hdf_obj_child, METH_VARARGS, NULL}, {"next", p_hdf_obj_next, METH_VARARGS, NULL}, {"name", p_hdf_obj_name, METH_VARARGS, NULL}, {"value", p_hdf_obj_value, METH_VARARGS, NULL}, {"top", p_hdf_obj_top, METH_VARARGS, NULL}, {"attrs", p_hdf_obj_attr, METH_VARARGS, NULL}, {"setValue", p_hdf_set_value, METH_VARARGS, NULL}, {"setAttr", p_hdf_set_attr, METH_VARARGS, NULL}, {"readFile", p_hdf_read_file, METH_VARARGS, NULL}, {"writeFile", p_hdf_write_file, METH_VARARGS, NULL}, {"writeFileAtomic", p_hdf_write_file_atomic, METH_VARARGS, NULL}, {"readString", p_hdf_read_string, METH_VARARGS, NULL}, {"writeString", p_hdf_write_string, METH_VARARGS, NULL}, {"removeTree", p_hdf_remove_tree, METH_VARARGS, NULL}, {"dump", p_hdf_dump, METH_VARARGS, NULL}, {"copy", p_hdf_copy, METH_VARARGS, NULL}, {"setSymLink", p_hdf_set_symlink, METH_VARARGS, NULL}, {"searchPath", p_hdf_search_path, METH_VARARGS, NULL}, {NULL, NULL} }; static PyObject * p_escape (PyObject *self, PyObject *args) { PyObject *rv; char *s; char *escape; char *esc_char; int buflen; char *ret = NULL; NEOERR *err; if (!PyArg_ParseTuple(args, "s#ss:escape(str, char, escape)", &s, &buflen, &esc_char, &escape)) return NULL; err = neos_escape(s, buflen, esc_char[0], escape, &ret); if (err) return p_neo_error(err); rv = Py_BuildValue("s", ret); free(ret); return rv; } static PyObject * p_unescape (PyObject *self, PyObject *args) { PyObject *rv; char *s; char *copy; char *esc_char; int buflen; if (!PyArg_ParseTuple(args, "s#s:unescape(str, char)", &s, &buflen, &esc_char)) return NULL; copy = strdup(s); if (copy == NULL) return PyErr_NoMemory(); neos_unescape(copy, buflen, esc_char[0]); rv = Py_BuildValue("s", copy); free(copy); return rv; } /* This returns the expanded version in the standard python time tuple * */ static PyObject * p_time_expand (PyObject *self, PyObject *args) { PyObject *rv; int tt; struct tm ttm; char *tz; if (!PyArg_ParseTuple(args, "is:time_expand(time_t, timezone string)", &tt, &tz)) return NULL; neo_time_expand(tt, tz, &ttm); rv = Py_BuildValue("(i,i,i,i,i,i,i,i,i)", ttm.tm_year + 1900, ttm.tm_mon + 1, ttm.tm_mday, ttm.tm_hour, ttm.tm_min, ttm.tm_sec, ttm.tm_wday, 0, ttm.tm_isdst); return rv; } static PyObject * p_time_compact (PyObject *self, PyObject *args) { PyObject *rv; int tt; struct tm ttm; int junk; char *tz; memset(&ttm, 0, sizeof(struct tm)); if (!PyArg_ParseTuple(args, "(i,i,i,i,i,i,i,i,i)s:time_compact(time tuple, timezone string)", &ttm.tm_year, &ttm.tm_mon, &ttm.tm_mday, &ttm.tm_hour, &ttm.tm_min, &ttm.tm_sec, &ttm.tm_wday, &junk, &ttm.tm_isdst, &tz)) return NULL; /* fix up difference between ttm and python tup */ ttm.tm_year -= 1900; ttm.tm_mon -= 1; tt = neo_time_compact (&ttm, tz); rv = Py_BuildValue("i", tt); return rv; } static PyMethodDef UtilMethods[] = { {"HDF", p_hdf_init, METH_VARARGS, NULL}, {"escape", p_escape, METH_VARARGS, NULL}, {"unescape", p_unescape, METH_VARARGS, NULL}, {"time_expand", p_time_expand, METH_VARARGS, NULL}, {"time_compact", p_time_compact, METH_VARARGS, NULL}, {NULL, NULL} }; PyObject *p_hdf_value_get_attr (HDFObject *ho, char *name) { return Py_FindMethod(HDFMethods, (PyObject *)ho, name); } DL_EXPORT(void) initneo_util(void) { PyObject *m, *d; HDFObjectType.ob_type = &PyType_Type; m = Py_InitModule("neo_util", UtilMethods); d = PyModule_GetDict(m); NeoError = PyErr_NewException("neo_util.Error", NULL, NULL); NeoParseError = PyErr_NewException("neo_util.ParseError", NULL, NULL); PyDict_SetItemString(d, "Error", NeoError); PyDict_SetItemString(d, "ParseError", NeoParseError); } clearsilver-0.10.5/python/p_neo_util.h0000644001211700116100000000477210261037514014664 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #ifndef __P_NEO_UTIL_H_ #define __P_NEO_UTIL_H_ 1 #include "util/neo_misc.h" #include "util/neo_hdf.h" #ifndef DL_EXPORT #define DL_EXPORT(x) x #endif __BEGIN_DECLS /* external HDF object interface. */ #define P_HDF_TO_OBJECT_NUM 0 #define P_HDF_TO_OBJECT_RETURN PyObject * #define P_HDF_TO_OBJECT_PROTO (HDF *data, int dealloc) #define P_OBJECT_TO_HDF_NUM 1 #define P_OBJECT_TO_HDF_RETURN HDF * #define P_OBJECT_TO_HDF_PROTO (PyObject *ho) #define P_NEO_ERROR_NUM 2 #define P_NEO_ERROR_RETURN PyObject * #define P_NEO_ERROR_PROTO (NEOERR *err) /* external CS object interface */ #define P_CS_TO_OBJECT_NUM 3 #define P_CS_TO_OBJECT_RETURN PyObject * #define P_CS_TO_OBJECT_PROTO (CSPARSE *data) #define P_NEO_CGI_POINTERS 4 #ifdef NEO_CGI_MODULE P_HDF_TO_OBJECT_RETURN p_hdf_to_object P_HDF_TO_OBJECT_PROTO; P_OBJECT_TO_HDF_RETURN p_object_to_hdf P_OBJECT_TO_HDF_PROTO; P_NEO_ERROR_RETURN p_neo_error P_NEO_ERROR_PROTO; P_CS_TO_OBJECT_RETURN p_cs_to_object P_CS_TO_OBJECT_PROTO; /* other functions */ void initneo_util(void); void initneo_cs(void); #else static void **NEO_PYTHON_API; #define p_hdf_to_object \ (*(P_HDF_TO_OBJECT_RETURN (*)P_HDF_TO_OBJECT_PROTO) NEO_PYTHON_API[P_HDF_TO_OBJECT_NUM]) #define p_object_to_hdf \ (*(P_OBJECT_TO_HDF_RETURN (*)P_OBJECT_TO_HDF_PROTO) NEO_PYTHON_API[P_OBJECT_TO_HDF_NUM]) #define p_neo_error \ (*(P_NEO_ERROR_RETURN (*)P_NEO_ERROR_PROTO) NEO_PYTHON_API[P_NEO_ERROR_NUM]) #define p_cs_to_object \ (*(P_CS_TO_OBJECT_RETURN (*)P_CS_TO_OBJECT_PROTO) NEO_PYTHON_API[P_CS_TO_OBJECT_NUM]) #define import_neo_cgi() \ { \ PyObject *module = PyImport_ImportModule("neo_cgi"); \ if (module != NULL) { \ PyObject *module_dict = PyModule_GetDict(module); \ PyObject *c_api_object = PyDict_GetItemString(module_dict, "_C_API"); \ PyObject *c_api_num_o = PyDict_GetItemString(module_dict, "_C_API_NUM"); \ if (PyInt_AsLong(c_api_num_o) < P_NEO_CGI_POINTERS) { \ PyErr_Format(PyExc_ImportError, "neo_cgi module doesn't match header compiled against, use of this module may cause a core dump: %ld < %ld", PyInt_AsLong(c_api_num_o), (long) P_NEO_CGI_POINTERS); \ } \ if (PyCObject_Check(c_api_object)) { \ NEO_PYTHON_API = (void **)PyCObject_AsVoidPtr(c_api_object); \ } \ } \ } #endif __END_DECLS #endif /* __P_NEO_UTIL_H_ */ clearsilver-0.10.5/python/setup.py0000755001211700116100000000741410645312525014073 00000000000000 import os, string, re, sys # Check to see if the Egg system is installed (ie, setuptools) # See http://peak.telecommunity.com/DevCenter/PythonEggs USE_EGGS=1 try: from setuptools import setup except ImportError: from distutils.core import setup USE_EGGS=0 from distutils.core import Extension from distutils import sysconfig VERSION = "0.10.5" INC_DIRS = ["../"] LIBRARIES = ["neo_cgi", "neo_cs", "neo_utl"] LIB_DIRS = ["../libs"] CC = "gcc" LDSHARED = "gcc -shared" ## ARGGH!! It looks like you can only specify a single item on the ## command-line or in the setup.cfg file for options which take multiple ## lists... and it overrides what is defined here. So I have to do all ## the work of the configure file AGAIN here. At least its in python, ## which is easier... ## Actually, forget that, I'm just going to load and parse the rules.mk ## file and build what I need if not os.path.exists("../rules.mk"): raise "You need to run configure first to generate the rules.mk file!" make_vars = { 'NEOTONIC_ROOT' : '..' } rules = open("../rules.mk").read() for line in string.split(rules, "\n"): parts = string.split(line, '=', 1) if len(parts) != 2: continue var, val = parts var = string.strip(var) make_vars[var] = val if var == "CFLAGS": matches = re.findall("-I(\S+)", val) inserted = [] for inc_path in matches: # inc_path = match.group(1) if inc_path not in INC_DIRS: inserted.append(inc_path) sys.stderr.write("adding inc_path %s\n" % inc_path) INC_DIRS = inserted + INC_DIRS elif var == "LIBS": matches = re.findall("-l(\S+)", val) inserted = [] for lib in matches: # lib = match.group(1) if lib not in LIBRARIES: inserted.append(lib) sys.stderr.write("adding lib %s\n" % lib) LIBRARIES = inserted + LIBRARIES elif var == "LDFLAGS": matches = re.findall("-L(\S+)", val) inserted = [] for lib_path in matches: # lib_path = match.group(1) if lib_path not in LIB_DIRS: inserted.append(lib_path) sys.stderr.write("adding lib_path %s\n" % lib_path) LIB_DIRS = inserted + LIB_DIRS elif var == "CC": CC = val elif var == "LDSHARED": LDSHARED = val def expand_var(var, vars): def replace_var(m, variables=vars): var = m.group(1) if var[:2] == "$(" and var[-1] == ")": var = variables.get(var[2:-1], "") return var while 1: new_var = re.sub('(\$\([^\)]*\))', replace_var, var) if new_var == var: break var = new_var return var.strip() def expand_vars(vlist, vars): nlist = [] for val in vlist: val = expand_var(val, vars) if val: nlist.append(val) return nlist INC_DIRS = expand_vars(INC_DIRS, make_vars) LIB_DIRS = expand_vars(LIB_DIRS, make_vars) LIBRARIES = expand_vars(LIBRARIES, make_vars) CC = os.environ.get('CC', expand_var(CC, make_vars)) LDSHARED = os.environ.get('LDSHARED', expand_var(CC, make_vars)) # HACK! The setup/Makefile may not have the hermetic/cross-compiler entries # for the compiler that we need, so override them here! given_cc = sysconfig.get_config_var('CC') if given_cc != CC and given_cc[0] != '/': sys.stderr.write("Overriding setup's CC from %s to %s\n" % (given_cc, CC)) try: sysconfig._config_vars['CC'] = CC sysconfig._config_vars['LDSHARED'] = LDSHARED except AttributeError: pass setup_args = { 'name': "clearsilver", 'version': VERSION, 'description': "Python ClearSilver Wrapper", 'author': "Brandon Long", 'author_email': "blong@fiction.net", 'url': "http://www.clearsilver.net/", 'ext_modules': [Extension( name="neo_cgi", sources=["neo_cgi.c", "neo_cs.c", "neo_util.c"], include_dirs=INC_DIRS, library_dirs=LIB_DIRS, libraries=LIBRARIES, )] } if USE_EGGS: setup_args['zip_safe'] = 0 apply(setup, [], setup_args) clearsilver-0.10.5/python/static.py0000755001211700116100000000215210261037514014210 00000000000000#!/usr/bin/env python import sys, os, traceback, string import neo_cgi def log (s): sys.stderr.write("CGI: %s\n" % s) def exceptionString(): import StringIO ## get the traceback message sfp = StringIO.StringIO() traceback.print_exc(file=sfp) exception = sfp.getvalue() sfp.close() return exception def main (argv, environ): # log ("starting") cgi = neo_cgi.CGI("") try: hdf_file = cgi.hdf.getValue("CGI.PathTranslated", "") if hdf_file == "": cgi.error ("No PATH_TRANSLATED var") return x = string.rfind (hdf_file, '/') if x != -1: cgi.hdf.setValue ("hdf.loadpaths.0", hdf_file[:x]) cgi.hdf.readFile(hdf_file) content = cgi.hdf.getValue("Content", "") if content == "": cgi.error ("No Content var specified in HDF file %s" % hdf_file) return cgi.display(content) except neo_cgi.CGIFinished: return except Exception, Reason: log ("Python Exception: %s" % (str(repr(Reason)))) s = neo_cgi.text2html("Python Exception: %s" % exceptionString()) cgi.error (s) if __name__ == "__main__": main (sys.argv, os.environ) clearsilver-0.10.5/python/upload.py0000755001211700116100000000150310261037514014204 00000000000000#!/usr/bin/env python import sys, os, traceback, string import neo_cgi def log (s): sys.stderr.write("CGI: %s\n" % s) def exceptionString(): import StringIO ## get the traceback message sfp = StringIO.StringIO() traceback.print_exc(file=sfp) exception = sfp.getvalue() sfp.close() return exception def main (argv, environ): # log ("starting") cgi = neo_cgi.CGI("") try: fp = cgi.filehandle("file") print "Content-Type: text/plain\r\n\r\n" data = fp.read() print data f = open("/tmp/file", "w") f.write(data) except neo_cgi.CGIFinished: return except Exception, Reason: log ("Python Exception: %s" % (str(repr(Reason)))) s = neo_cgi.text2html("Python Exception: %s" % exceptionString()) cgi.error (s) if __name__ == "__main__": main (sys.argv, os.environ) clearsilver-0.10.5/scripts/0000755001211700116100000000000010645505045012577 500000000000000clearsilver-0.10.5/scripts/ChangeLog.py0000755001211700116100000001633410261037515014726 00000000000000#!/neo/opt/bin/python import sys, os, string, re, getopt, pwd, socket, time def warn(*args): t = time.time() log_line = "[" + time.strftime("%m/%d %T", time.localtime(t)) + "] " l = [] for arg in args: l.append(str(arg)) log_line = log_line + string.join(l, " ") + "\n" sys.stderr.write(log_line) class ChangeLog: def __init__ (self, module, release_from, release_to, copydir = None, cvsroot=None): self._module = module self._releaseFrom = release_from self._releaseTo = release_to self._cvsroot = cvsroot if cvsroot is None: self._cvsroot = os.environ.get("CVSROOT", None) self._copydir = copydir if copydir is None: self._copydir = os.getcwd() self._names = {} def changeInfo (self): cmd = self.cvsCmd ("-q", "rdiff", "-s -r%s -r%s %s" % (self._releaseFrom, self._releaseTo, self._module)) warn (cmd) fpi = os.popen (cmd) data = fpi.readlines() r = fpi.close() if r is None: r = 0 if r != 0: warn ("Return code from command is %d\n" % r) return self.oldfiles = {} self.newfiles = [] self.delfiles = [] old_re = re.compile ("File (.*) changed from revision (.*) to (.*)") new_re = re.compile ("File (.*) is new; current revision (.*)") del_re = re.compile ("File (.*) is removed;") for line in data: m = old_re.match (line) if m: file = m.group(1) if file[:len(self._module)+1] == "%s/" % self._module: file = file[len(self._module)+1:] self.oldfiles[file] = (m.group(2), m.group(3)) continue m = new_re.match (line) if m: file = m.group(1) if file[:len(self._module)+1] == "%s/" % self._module: file = file[len(self._module)+1:] self.newfiles.append(file) continue m = del_re.match (line) if m: file = m.group(1) if file[:len(self._module)+1] == "%s/" % self._module: file = file[len(self._module)+1:] self.delfiles.append(file) continue warn ("Unknown response from changeInfo request:\n %s" % line) def parselog (self, log): lines = string.split (log, '\n') in_header = 1 x = 0 num = len(lines) revisions = {} revision = None comment = [] info_re = re.compile ("date: ([^; ]*) ([^;]*); author: ([^;]*);") while (x < num): line = string.strip(lines[x]) if line: if (x + 1 < num): nline = string.strip(lines[x+1]) else: nline = None if in_header: (key, value) = string.split (line, ':', 1) if key == "Working file": filename = string.strip (value) elif key == "description": in_header = 0 else: if (line == "----------------------------") and (nline[:9] == "revision "): if revision is not None: key = (date, author, string.join (comment, '\n')) try: revisions[key].append((filename, revision)) except KeyError: revisions[key] = [(filename, revision)] comment = [] elif line == "=" * 77: key = (date, author, string.join (comment, '\n')) try: revisions[key].append((filename, revision)) except KeyError: revisions[key] = [(filename, revision)] in_header = 1 revision = None comment = [] elif line[:9] == "revision ": (rev, revision) = string.split (lines[x]) else: m = info_re.match (lines[x]) if m: date = m.group(1) author = m.group(3) else: comment.append (lines[x]) x = x + 1 return revisions def rcs2log (self): cwd = os.getcwd() os.chdir(self._copydir) files = string.join (self.oldfiles.keys(), ' ') cmd = 'rcs2log -v -r "-r%s:%s" %s' % (self._releaseFrom, self._releaseTo, files) fpi = os.popen (cmd) data = fpi.read() r = fpi.close() os.chdir(cwd) if r is None: r = 0 if r != 0: warn (cmd) warn ("Return code from command is %d\n" % r) return fpo = open ("ChangeLog.%s" % self._releaseTo, 'w') fpo.write(data) fpo.close() def runCmd (self, cmd): cwd = os.getcwd() os.chdir(self._copydir) warn (cmd) fpi = os.popen (cmd) data = fpi.read() r = fpi.close() os.chdir(cwd) if r is None: r = 0 if r != 0: warn ("Return code from command is %d\n" % r) return None return data def rcslog (self): inverted_log = {} if len(self.newfiles): cmd = self.cvsCmd ("", "log", "-N %s" % string.join(self.newfiles,' ')) data = self.runCmd (cmd) if data is None: return revisions = self.parselog (data) for (key, value) in revisions.items(): try: inverted_log[key] = inverted_log[key] + value except KeyError: inverted_log[key] = value filenames = string.join (self.oldfiles.keys(), ' ') if filenames: cmd = self.cvsCmd ("", "log", "-N -r%s:%s %s" % (self._releaseFrom, self._releaseTo, filenames)) data = self.runCmd (cmd) if data is not None: revisions = self.parselog (data) for (key, value) in revisions.items(): for (filename, revision) in value: (rev1, rev2) = self.oldfiles[filename] if revision != rev1: try: inverted_log[key].append((filename, revision)) except KeyError: inverted_log[key] = [(filename, revision)] fpo = open ("ChangeLog.%s" % self._releaseTo, 'w') fpo.write ("ChangeLog from %s to %s\n" % (self._releaseFrom, self._releaseTo)) fpo.write ("=" * 72 + "\n") changes = inverted_log.items() changes.sort() changes.reverse() last_stamp = "" for (key, value) in changes: (date, author, comment) = key new_stamp = "%s %s" % (date, self.fullname(author)) if new_stamp != last_stamp: fpo.write ("%s\n\n" % new_stamp) last_stamp = new_stamp for (filename, revision) in value: fpo.write (" * %s:%s\n" % (filename, revision)) fpo.write (" %s\n\n" % comment) fpo.close() def cvsCmd (self, cvsargs, cmd, cmdargs): root = "" if self._cvsroot is not None: root = "-d %s" % self._cvsroot cmd = "cvs -z3 %s %s %s %s" % (root, cvsargs, cmd, cmdargs) return cmd def fullname (self, author): try: return self._names[author] except KeyError: try: (name, passwd, uid, gid, gecos, dir, shell) = pwd.getpwnam(author) fullname = "%s <%s@%s>" % (gecos, name, socket.gethostname()) except KeyError: fullname = author self._names[author] = fullname return fullname def usage (argv0): print "usage: %s [--help] module release1 release2" % argv0 print __doc__ def main (argv, stdout, environ): list, args = getopt.getopt(argv[1:], "", ["help"]) for (field, val) in list: if field == "--help": usage (argv[0]) return if len (args) < 3: usage (argv[0]) return cl = ChangeLog (args[0], args[1], args[2]) cl.changeInfo() cl.rcslog() if __name__ == "__main__": main (sys.argv, sys.stdout, os.environ) clearsilver-0.10.5/scripts/commitlog.py0000755001211700116100000000412310261037515015062 00000000000000#!/usr/bin/python # commitlog.py # # Written July 2001 by David W. Jeske # # Released freely into the public domain. # # parse CVS commit logs and make nice submit logs... # import sys import os import string import time def main(argv): PATH = argv[1] module = argv[2] body = sys.stdin.read() body_lines = string.split(body,"\n") mode = 0 mod_files = [] add_files = [] rem_files = [] log_lines = [] for a_line in body_lines: if a_line == "Modified Files:": mode = "modfiles" elif a_line == "Added Files:": mode = "addfiles" elif a_line == "Log Message:": mode = "loglines" elif a_line == "Removed Files:": mode = "remfiles" else: if mode == "modfiles": mod_files.append(string.strip(a_line)) elif mode == "addfiles": add_files.append(string.strip(a_line)) elif mode == "loglines": log_lines.append(a_line) elif mode == "remfiles": rem_files.append(string.strip(a_line)) # if files don't exist, we should create them... CVS_USER = os.environ['LOGNAME'] DATE = time.strftime( "%I:%M%p %Y/%m/%d", time.localtime(time.time())) log_summary = "%10s %16s %s\n" % (CVS_USER,DATE,string.join(log_lines," ")[:60]) filename = os.path.join(PATH,"%s.summary" % module) os.system('co -f -q -l %s %s,v' % (filename,filename)) # check to see if the log line is already there fps = open(filename,"a+") try: fps.seek(-len(log_summary),2) check_data = fps.read(len(log_summary)) if check_data != log_summary: fps.write(log_summary) except IOError: # Not enough data to go back that far fps.write(log_summary) fps.close() os.system('ci -q -m"none" %s %s,v' % (filename,filename)) log_data = "----------------\n" + "USER: %s\n" % CVS_USER + "DATE: %s\n" % DATE + body filename = os.path.join(PATH,"%s" % module) os.system('co -f -q -l %s %s,v' % (filename,filename)) fp = open(filename,"a+") fp.write(log_data) fp.close() os.system('ci -q -m"none" %s %s,v' % (filename,filename)) if __name__ == "__main__": main(sys.argv) clearsilver-0.10.5/scripts/cs_lint.py0000755001211700116100000001735210261037515014533 00000000000000#!/usr/bin/python #!/neo/opt/bin/python import sys, string, os, getopt, signal, time sys.path.append("../python") import neo_cgi, neo_util import cStringIO class ClearSilverChecker: def __init__ (self): self.context = "" self.data = "" self.at = 0 self.cmd = "" self.tokens = [] def error(self, s): lineno = self.lineno(self.data, self.at) print "-E- [%s:%d] %s" % (self.context, lineno, s) if self.cmd: print " Command is %s" % self.cmd if self.tokens: print " Tokens: %s" % repr(self.tokens) def warn(self, s): lineno = self.lineno(self.data, self.at) print "-W- [%s:%d] %s" % (self.context, lineno, s) if self.cmd: print " Command is %s" % self.cmd if self.tokens: print " Tokens: %s" % repr(self.tokens) def check_file(self, filename): print "Checking file %s" % filename self.context = filename try: self.run_neo_cgi(filename) except neo_util.ParseError, reason: print "-E- %s" % str(reason) self.data = open(filename, "r").read() self.parse() def run_neo_cgi(self, filename): stdin = cStringIO.StringIO("") stdout = cStringIO.StringIO() neo_cgi.cgiWrap(stdin, stdout, {}) neo_cgi.IgnoreEmptyFormVars(1) ncgi = neo_cgi.CGI() path = os.path.dirname(filename) ncgi.hdf.setValue("hdf.loadpaths.path", path) ncgi.display(filename) return def lineno(self, data, i): return len(string.split(data[:i], '\n')) def parse(self): self.at = 0 x = string.find(self.data[self.at:], '= 0: self.at = x + self.at ce = string.find(self.data[self.at:], '?>') if ce == -1: self.error("Missing ?> in expression") else: ce = ce + self.at self.check_command(ce) # reset these class variables self.cmd = "" self.tokens = [] self.at = self.at + 1 x = string.find(self.data[self.at:], ' %s" % (cmd, args) if cmd == "alt": self.check_expression(args) elif cmd == "if": self.check_expression(args) elif cmd == "elif": self.check_expression(args) elif cmd == "else": pass elif cmd == "include": self.check_expression(args) elif cmd == "linclude": self.check_expression(args) elif cmd == "name": self.check_expression(args) elif cmd == "var": self.check_expression(args) elif cmd == "evar": self.check_expression(args) elif cmd == "lvar": self.check_expression(args) elif cmd == "def": macro, args = self.split_macro(args) if macro: self.check_expression(macro, lvalue=1) if args:self.check_expression(args) elif cmd == "call": macro, args = self.split_macro(args) if macro: self.check_expression(macro, lvalue=1) if args:self.check_expression(args) elif cmd == "with": varname, args = self.split_equals(args) if varname: self.check_expression(varname, lvalue=1) if args: self.check_expression(args) elif cmd == "each": varname, args = self.split_equals(args) if varname: self.check_expression(varname, lvalue=1) if args: self.check_expression(args) elif cmd == "loop": varname, args = self.split_equals(args) if varname: self.check_expression(varname, lvalue=1) if args: self.check_expression(args) elif cmd == "set": varname, args = self.split_equals(args) if varname: self.check_expression(varname, lvalue=1) if args: self.check_expression(args) else: self.error("Unrecognized command %s" % cmd) def split_equals(self, args): x = string.find(args, '=') if x == -1: self.error("Missing equals") return None, None else: return args[:x], args[x+1:] def split_macro(self, args): b = string.find(args, '(') e = string.rfind(args, ')') if b == -1: self.error("Missing opening parenthesis") return None, None if e == -1: self.error("Missing closing parenthesis") return None, None macro_name = args[:b] args = args[b+1:e] return macro_name, args def check_expression(self, expr, lvalue=0): tokens = self.tokenize_expression(expr) #print repr(tokens) if len(tokens) == 0: self.error("Empty Expression") _OP = 1 _VAR = 2 _VARN = 3 _STR = 4 _NUM = 5 _TOKEN_SEP = "\"?<>=!#-+|&,)*/%[]( \t\r\n" def tokenize_expression(self, expr): self.tokens = [] while expr: #print "expr: '%s'" % expr expr = string.lstrip(expr) len_expr = len(expr) if len_expr == 0: break if expr[:2] in ["<=", ">=", "==", "!=", "||", "&&"]: self.tokens.append((ClearSilverChecker._OP, expr[:2])) expr = expr[2:] continue elif expr[0] in ["!", "?", "<", ">", "+", "-", "*", "/", "%", "(", ")", "[", "]", ".", ',']: self.tokens.append((ClearSilverChecker._OP, expr[0])) expr = expr[1:] continue elif expr[0] in ["#", "$"]: x = 1 if expr[1] in ['+', '-']: x=2 while len_expr > x and expr[x] not in ClearSilverChecker._TOKEN_SEP: x=x+1 if x == 0: self.error("[1] Zero length token, unexpected character %s" % expr[0]) x = 1 else: token = expr[1:x] if expr[0] == "#": try: n = int(token) t_type = ClearSilverChecker._NUM except ValueError: t_type = ClearSilverChecker._VARN else: t_type = ClearSilverChecker._VAR self.tokens.append((t_type, token)) expr = expr[x:] continue elif expr[0] in ['"', "'"]: x = string.find(expr[1:], expr[0]) if x == -1: self.error("Missing end of string %s " % expr) break else: x = x + 1 self.tokens.append((ClearSilverChecker._STR, expr[1:x])) expr = expr[x+2:] continue else: x = 0 while len_expr > x and expr[x] not in ClearSilverChecker._TOKEN_SEP: x=x+1 if x == 0: self.error("[2] Zero length token, unexpected character %s" % expr[0]) x = 1 else: token = expr[:x] try: n = int(token) t_type = ClearSilverChecker._NUM self.warn("This behavior changed in version 0.9: previously this was a variable name, now its a number: %s" % token) except ValueError: t_type = ClearSilverChecker._VAR self.tokens.append((t_type, token)) expr = expr[x:] continue return self.tokens # For version 0.9, we changed two things, we should check for them # both # - an all numeric expression element is now considered a number and # not an HDF variable name # - we now use boolean evaluation in places that used to use either a # special case or a numeric evaluation def usage(argv0): print "%s: usage info!!" % argv0 def main(argv): alist, args = getopt.getopt(argv[1:], "", ["help"]) for (field, val) in alist: if field == "--help": usage(argv[0]) sys.exit(-1) for file in args: ClearSilverChecker().check_file(file) if __name__ == "__main__": main(sys.argv) clearsilver-0.10.5/scripts/document.py0000755001211700116100000002232710645504751014723 00000000000000#!/usr/bin/env python """ document.py -- Simple script to generate manpages from C header files. Looks for the following formatted C comments in the C header files: /* * Function: my_function - This is my function * Description: My function does the following things, in no particular * order: It eats, sleeps, and is merry * Input: arg1 - This argument is healthy * arg2 - This argument is wealthy * arg3 - This argument is wise * Output: arg4 - The location of the porridge * arg5 - The location of the spider * Returns: -1 on error, 0 otherwise */ """ import sys, os, getopt, string, re, time QUIET = 0 def usage(argv0): print "%s [--help]" % argv0 class FuncDoc: def __init__ (self, name): self._name = name self._title = None self._desc = None self._args = None self._retr = None self._defn = None self._output = None self._other = "" def __repr__(self): out = [] out.append("Name: %s" % self._name) if self._title is not None: out.append("Title: %s" % self._title) if self._desc is not None: out.append("Description: %s" % self._desc) if self._args is not None: out.append("Input: %s" % self._args) if self._output is not None: out.append("Output: %s" % self._output) if self._retr is not None: out.append("Returns: %s" % self._retr) if string.strip(self._other): out.append("Other: %s" % self._other) if self._defn is not None: out.append("Definition:") out.append(self._defn) return string.join(out, "\n") class CParser: STATE_OTHER = 0 STATE_COMT = 1 STATE_FUNC = 2 RE_C_comment = re.compile("/\*(.*)") RE_C_define = re.compile("\s*#\s*define (\S+) (.*)") RE_C_typedef = re.compile("typedef (\S+) (.*)") RE_C_func_def = re.compile("[^#]*(\S+)([ \*]+)(\S+)\s*\([^\)]*\);") RE_C_func_def_b = re.compile("[^#]*(\S+)([ \*]+)(\S+)\s*\([^\)]*") RE_C_func_com = re.compile("function:\s*(\S+)(.*)", re.IGNORECASE) RE_C_desc_com = re.compile("description:\s*(.+)", re.IGNORECASE) RE_C_args_com = re.compile("(arguments|input):\s*(.+)", re.IGNORECASE) RE_C_retr_com = re.compile("(return|returns):\s*(.+)", re.IGNORECASE) RE_C_out_com = re.compile("output:\s*(.+)", re.IGNORECASE) RE_C_other_com = re.compile("(\S+):\s*(.+)") RE_C_com_cont = re.compile("[ \*]*(.+)") def __init__ (self, filename): self._filename = filename self._funcs = {} def func (self, name): try: return self._funcs[name] except KeyError: f = FuncDoc(name) self._funcs[name] = f return f def go(self): try: fp = open(self._filename) except IOError: return state = CParser.STATE_OTHER f = None cont = None while 1: line = fp.readline() if not line: break if state == CParser.STATE_OTHER: m = CParser.RE_C_comment.search (line) if m: line = m.group(1) state = CParser.STATE_COMT else: m = CParser.RE_C_define.match(line) if m: continue m = CParser.RE_C_typedef.search(line) if m: continue m = CParser.RE_C_func_def.match(line) if m: func_name = m.group(3) f = self.func(func_name) f._defn = line else: m = CParser.RE_C_func_def_b.match(line) if m: state = CParser.STATE_FUNC func_name = m.group(3) f = self.func(func_name) f._defn = line continue if state == CParser.STATE_COMT: if string.find(line, "*/") != -1: state = CParser.STATE_OTHER continue m = CParser.RE_C_func_com.search(line) if m: cont = "func" f = self.func(m.group(1)) f._title = m.group(2) continue m = CParser.RE_C_desc_com.search(line) if m: cont = "desc" f._desc = m.group(1) continue m = CParser.RE_C_args_com.search(line) if m: cont = "args" f._args = m.group(2) continue m = CParser.RE_C_retr_com.search(line) if m: cont = "retr" f._retr = m.group(2) continue m = CParser.RE_C_out_com.search(line) if m: cont = "out" f._output = m.group(1) continue m = CParser.RE_C_other_com.search(line) if not f: continue if m: cont = "other" f._other = f._other + "%s: %s" % (m.group(1), m.group(2)) continue m = CParser.RE_C_com_cont.search(line) if m: if cont == "func": f._title = f._title + '\n' + m.group(1) elif cont == "desc": f._desc = f._desc + '\n'+ m.group(1) elif cont == "args": f._args = f._args + '\n' + m.group(1) elif cont == "retr": f._retr = f._retr + '\n' + m.group(1) elif cont == "out": f._output = f._output + '\n' + m.group(1) elif cont == "other": f._other = f._other + '\n' + m.group(1) elif state == CParser.STATE_FUNC: f._defn = f._defn+line if string.find(line, ");") != -1: state = CParser.STATE_OTHER def dump(self): for name in self._funcs.keys(): # print name print "%s\n" % self._funcs[name] def dump_manpages(self, directory, owner): global QUIET date = time.strftime("%d %B %Y", time.localtime(time.time())) for name, f in self._funcs.items(): if f._title is None and f._desc is None and f._args is None and f._retr is None: if not QUIET: sys.stderr.write('-W- No info for function "%s()"\n' % name) continue if f._defn is None: if not QUIET: sys.stderr.write('-W- No defn for function "%s()"\n' % name) fp = open("%s/%s.3" % (directory, name), "w") fp.write('.TH %s 3 "%s" "%s" "%s"\n\n' % (name, date, owner, self._filename)) fp.write('.de Ss\n.sp\n.ft CW\n.nf\n..\n') fp.write('.de Se\n.fi\n.ft P\n.sp\n..\n') fp.write('.SH NAME\n') if f._title is None: fp.write('%s\n' % f._name) else: fp.write('%s %s\n' % (f._name, f._title)) fp.write('.SH SYNOPSIS\n') fp.write('.Ss\n#include <%s>\n.Se\n' % self._filename) if f._defn: fp.write('.Ss\n%s\n.Se\n' % f._defn) else: fp.write('.Ss\n%s()\n.Se\n' % f._name) fp.write('\n') if f._args: fp.write('.SH ARGUMENTS\n') fp.write('%s\n\n' % string.replace(f._args, '\n', '\n.br\n')) if f._desc or string.strip(f._other): fp.write('.SH DESCRIPTION\n') if f._desc: fp.write('%s\n\n' % f._desc) if string.strip(f._other): fp.write('%s\n\n' % f._other) if f._output: fp.write('.SH "RETURN VALUE"\n') fp.write('%s\n\n' % string.replace(f._output, '\n', '\n.br\n')) fp.write('.SH "SEE ALSO"\n') fp.write('.BR %s\n' % string.join(self._funcs.keys(), ' "(3), "')) fp.close() def dump_hdf (self, directory, owner): global QUIET sys.path.insert (0, "../python") sys.path.insert (0, "python") import neo_cgi, neo_util hdf = neo_util.HDF() date = time.strftime("%d %B %Y", time.localtime(time.time())) if not self._funcs.items(): return for name, f in self._funcs.items(): if f._title is None and f._desc is None and f._args is None and f._retr is None: if not QUIET: sys.stderr.write('-W- No info for function "%s()"\n' % name) continue if f._defn is None: if not QUIET: sys.stderr.write('-W- No defn for function "%s()"\n' % name) hdf.setValue ("Code.%s" % name, name) obj = hdf.getObj ("Code.%s" % name) obj.setValue ("Name", name) obj.setValue ("filename", self._filename) if f._title: obj.setValue ("Title", f._title) if f._defn: obj.setValue ("Define", neo_cgi.text2html(f._defn)) if f._args: obj.setValue ("Args", neo_cgi.text2html(f._args)) if f._desc: obj.setValue ("Desc", neo_cgi.text2html(f._desc)) if string.strip(f._other): obj.setValue ("Other", neo_cgi.text2html(string.strip(f._other))) if f._output: obj.setValue ("Output", neo_cgi.text2html(f._output)) n = 0 for func in self._funcs.keys(): obj.setValue ("related.%d" % n, func) n = n + 1 fname = self._filename x = string.rindex (fname, "/") if x != -1: fname = fname[x+1:] x = string.rindex (fname, '.') if x != -1: fname = fname[:x] hdf.writeFile ("%s/%s.hdf" % (directory, fname)) def main(argv, environ): alist, args = getopt.getopt(argv[1:], "q", ["help", "outdir=", "owner=", "hdf"]) outdir = "." owner = "" do_hdf = 0 for (field, val) in alist: if field == "--help": usage (argv[0]) return if field == "--outdir": outdir = val if field == "--owner": owner = val if field == "-q": global QUIET QUIET = 1 if field == "--hdf": do_hdf = 1 if args: for file in args: parser = CParser(file) parser.go() if not do_hdf: parser.dump_manpages(outdir, owner) else: parser.dump_hdf (outdir, owner) if __name__ == "__main__": main (sys.argv, os.environ) clearsilver-0.10.5/mod_ecs/0000755001211700116100000000000010645505045012521 500000000000000clearsilver-0.10.5/mod_ecs/Makefile0000644001211700116100000000116010455366521014102 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk MOD_ECS_SRC = mod_ecs.c MOD_ECS_SO = mod_ecs.so DLIBS += -lneo_cgi -lneo_cs -lneo_utl LIBS += $(DLIBS) $(DB2_LIB) TARGETS = $(MOD_ECS_SO) all: $(TARGETS) $(MOD_ECS_SO): $(MOD_ECS_SRC) $(DEP_LIBS) $(APXS) -c -o $@ $(MOD_ECS_SRC) install: all $(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(libexecdir) $(INSTALL) $(MOD_ECS_SO) $(DESTDIR)$(libexecdir) # Hmm, install it in the default apache place, or in with the # rest of our stuff? # $(APXS) -i $(MOD_ECS_SO) clean: $(RM) *.o distclean: $(RM) Makefile.depends $(TARGETS) *.o clearsilver-0.10.5/mod_ecs/Makefile.tmpl0000644001211700116100000000002710261037512015044 00000000000000# Makefile for mod_ecs clearsilver-0.10.5/mod_ecs/README0000644001211700116100000000725310261037512013321 00000000000000mod_ecs - Apache Embedded ClearSilver CGI Module ------------------------------------------------------- mod_ecs is based on a heavily modified version of mod_ecgi from: http://www.webthing.com/software/mod_ecgi.html This directory contains an Apache module which is designed to work with the ClearSilver CGI Kit. The point of this Apache module is performance, if your server is under sufficient load that the overhead of forking and execing the CGI for every request is too much, this module is for you. This module is also useful if you want some of the benefits of having a long-lived program: ie, the CGI can maintain connections to data sources such as databases or cache data in memory. The chief disadvantage is the same thing: your CGI becomes a long lived process, and you have to watch that you don't hold connections or memory that you don't want to. You might want to look into the Apache configuration directives for limiting the number of connections that each child process handles: MaxRequestsPerChild. If you are already using the full ClearSilver CGI Kit, all you need to do to compile for the embedded ClearSilver is compile to a shared library instead of to an executable. For instance, under Linux: Executable: ld -o static.cgi -lneo_cgi -lneo_cs -lneo_util Shared Library: ld -shared -fPic -o static.cso -lneo_cgi -lneo_cs -lneo_util Also, remember not to call exit(), as this will cause the entire Apache child to exit. There are two extra functions you can have in your CGI that the embedded ClearSilver module will try to find and call if they exist. They are: void ECSInit(void); and void ECSCleanup(void); The first is called when the embedded CGI is loaded, the second before the embedded CGI is unloaded. This module supports the following three Apache configuration directives: ECSReload When yes, mod_ecs will stat the .cso every time its run, to see if the file on disk has been updated. If it has been updated, it will reload the shared file from disk. This incurs some performance overhead, and when a change does occur, it removes most of the gains of ECSPreload. Notice also that on many operating systems, changing a shared library on disk that has been demand loaded can cause problems such as unexpected core dumps. This setting is most useful for development environments where speed/throughput requirements aren't as high, but constant change is a factor. ECSDepLib Brings the benefits of ECSPreload to dependent shared libraries. Will cause mod_ecs to dlopen() the library at apache initialization time. This can be avoided by using ECSPreload and having an ECSInit() function in your library which does the shared library initialization. ECSPreload This function can be used to preload any shared libraries that you might be calling later. This allows you to hide the latency of load/init time from your users by doing it once at apache initialization. Requirements: A later version of Apache 1.3.x, probably 1.3.12+. To Compile: To dynamically load this module (assuming your copy of Apache is compiled to use mod_so), do: /path/to/apxs -c mod_ecs.c Optionally, to (semi-)automatically install the module, do: /path/to/apxs -i -a -n ecs mod_ecs.so Or, you can just edit your httpd.conf file yourself, adding the following lines: LoadModule ecs_module /path/to/installed/mod_ecs.so # This line needs to be after and ClearModuleList command AddModule mod_ecs.c There are two ways to tell Apache that a file is an embedded ClearSilver CGI shared library, both are by extension. Typically, we use the .cso extension. You can either use AddHandler or AddType: AddHandler ecs-cgi .cso AddType application/x-ecs-cgi clearsilver-0.10.5/mod_ecs/mod_ecs.c0000644001211700116100000005317610405133747014232 00000000000000/* mod_ecs - Embedded ClearSilver CGI Apache Module mod_ecs is a heavily modified version of mod_ecgi from: http://www.webthing.com/software/mod_ecgi.html This version is designed to run with the ClearSilver CGIKit, specifically with the cgi_wrap calls from that kit. Those calls wrap the standard CGI access methods, namely environment variables and stdin/stdout, allowing those calls to be replaced easily. mod_ecs provides replacement calls which interface directly with the Apache internals. Additionally, mod_ecs is designed to dlopen() the shared library CGI once, and keep it in memory, making the CGI almost identical in performance to a regular Apache module. The fact that your CGI will be called multiple times is the biggest difference you can expect from a standard ClearSilver based CGI. This means your code must be clean! ECS - Embedded ClearSilver Platform: UNIX only. Anyone who wants to is welcome to port it elsewhere. ======================================================= To COMPILE Apache with embedded CGI support, use -ldl in EXTRA_LIBS possibly -rdynamic in EXTRA_LFLAGS I took this out of the config because its not there on freebsd4 = ConfigStart LIBS="$LIBS -ldl" = ConfigEnd (or as required by your platform) OK, here's for APACI: * MODULE-DEFINITION-START * Name: ecs_module * MODULE-DEFINITION-END ======================================================= ======================================================= BUGS Lots - here are some obvious ones - won't work with NPH - No mechanism is provided for running from an SSI - Can't take part in content-negotiation - No graceful cleanup if a CGI program crashes (though it's OK if the CGI fails but returns). - Suspected memory leak inherited from Apache (which ignores it because it happens just before exit there). */ #include #include "mod_ecs.h" #include "httpd.h" #include "http_config.h" #include "http_request.h" #include "http_core.h" #include "http_protocol.h" #include "http_main.h" #include "http_log.h" #include "util_script.h" #include "http_conf_globals.h" module ecs_module; /* Configuration stuff */ #define log_reason(reason,name,r) ap_log_error(APLOG_MARK,APLOG_ERR,(r)->server,(reason),(name)) #define log_scripterror(r,conf,ret,error) (log_reason((error),(r)->filename,(r)),ret) char** ecs_create_argv(pool*,char*,char*,char*,char*,const char*); /**************************************************************** * * Actual CGI handling... */ const int ERROR = 500; const int INTERNAL_REDIRECT = 3020; #undef ECS_DEBUG /****************************************************************** * cgiwrap routines * We've replaced all the normal CGI api calls with calls to the * appropriate cgiwrap routines instead. Then, we provide versions of * the cgiwrap callback here that interface directly with apache. We * need to mimic a bunch of the stuff that apache does in mod_cgi in * order to implement the output portion of the CGI spec. */ typedef struct header_buf { char *buf; int len; int max; int loc; int nonl; } HEADER_BUF; typedef struct wrap_data { HEADER_BUF hbuf; int end_of_header; int returns; request_rec *r; } WRAPPER_DATA; static int buf_getline (const char *idata, int ilen, char *odata, int olen, int *nonl) { char *eol; int len; *nonl = 1; eol = strchr (idata, '\n'); if (eol == NULL) { len = ilen; } else { *nonl = 0; len = eol - idata + 1; } if (len > olen) len = olen; memcpy (odata, idata, len); odata[len] = '\0'; return len; } static int h_getline (char *buf, int len, void *h) { HEADER_BUF *hbuf = (HEADER_BUF *)h; int ret; buf[0] = '\0'; if (hbuf->loc > hbuf->len) return 0; ret = buf_getline (hbuf->buf + hbuf->loc, hbuf->len - hbuf->loc, buf, len, &(hbuf->nonl)); hbuf->loc += ret; #if ECS_DEBUG>1 fprintf (stderr, "h_getline: [%d] %s\n", ret, buf); #endif return ret; } static int header_write (HEADER_BUF *hbuf, const char *data, int dlen) { char buf[1024]; int done, len; int nonl = hbuf->nonl; done = 0; while (done < dlen) { nonl = hbuf->nonl; len = buf_getline (data + done, dlen - done, buf, sizeof(buf), &(hbuf->nonl)); if (len == 0) break; done += len; if (hbuf->len + len > hbuf->max) { hbuf->max *= 2; if (hbuf->len + len > hbuf->max) { hbuf->max += len + 1; } hbuf->buf = (char *) realloc ((void *)(hbuf->buf), hbuf->max); } memcpy (hbuf->buf + hbuf->len, buf, len); hbuf->len += len; if (!nonl && (buf[0] == '\n' || buf[0] == '\r')) { /* end of headers */ return done; } } return 0; } /* The normal CGI module passes the returned data through * ap_scan_script_header(). We can't do that directly, since we don't * have a constant stream of data, so we buffer the header into our own * structure, and call ap_scan_script_header_err_core() with our own * getline() function to walk the header buffer we have. We could * probably get some speed improvement by keeping the header buffer * between runs, instead of growing it every time... for later. Also, * we currently don't use the pool allocation routines here, so we have * to be very careful not to leak. We could probably at least use the * ap_register_cleanup() function to make sure we clean up our mess... */ static int wrap_write (void *data, const char *buf, size_t len) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; int wl; int ret; #if ECS_DEBUG>1 fprintf (stderr, "wrap_write (%s, %d)\n", buf, len); #endif if (!wrap->end_of_header) { wl = header_write (&(wrap->hbuf), buf, len); if (wl == 0) { return len; } wrap->end_of_header = 1; wrap->hbuf.loc = 0; #if ECS_DEBUG>1 fprintf (stderr, "ap_scan_script_header_err_core\n%s\n", wrap->hbuf.buf); #endif wrap->returns = ap_scan_script_header_err_core(wrap->r, NULL, h_getline, (void *)&(wrap->hbuf)); #if ECS_DEBUG>1 fprintf (stderr, "ap_scan_script_header_err_core.. done\n"); #endif if (len >= wl) { len = len - wl; buf = buf + wl; } if (wrap->returns == OK) { const char* location = ap_table_get (wrap->r->headers_out, "Location"); if (location && location[0] == '/' && wrap->r->status == 200) { wrap->returns = INTERNAL_REDIRECT; } else if (location && wrap->r->status == 200) { /* XX Note that if a script wants to produce its own Redirect * body, it now has to explicitly *say* "Status: 302" */ wrap->returns = REDIRECT; } else { #ifdef ECS_DEBUG fprintf (stderr, "ap_send_http_header\n"); #endif ap_send_http_header(wrap->r); #ifdef ECS_DEBUG fprintf (stderr, "ap_send_http_header.. done\n"); #endif } } } /* if header didn't return OK, ignore the rest */ if ((wrap->returns != OK) || wrap->r->header_only) { return len; } #if ECS_DEBUG>1 fprintf (stderr, "ap_rwrite(%s,%d)\n", buf, len); #endif ret = ap_rwrite (buf, len, wrap->r); #if ECS_DEBUG>1 fprintf (stderr, "ap_rwrite.. done\n"); #endif return ret; } int wrap_vprintf (void *data, const char *fmt, va_list ap) { char buf[4096]; int len; len = ap_vsnprintf (buf, sizeof(buf), fmt, ap); return wrap_write (data, buf, len); } static int wrap_read (void *data, char *buf, size_t len) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; int ret; int x = 0; #if ECS_DEBUG>1 fprintf (stderr, "wrap_read (%s, %d)\n", buf, len); #endif do { ret = ap_get_client_block(wrap->r, buf + x, len - x); if (ret <= 0) break; x += ret; } while (x < len); #if ECS_DEBUG>1 fprintf (stderr, "done ap_get_client_block\n"); #endif if (ret < 0) return ret; return x; } static char *wrap_getenv (void *data, const char *s) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; char *v; v = (char *) ap_table_get (wrap->r->subprocess_env, s); if (v) return strdup(v); return NULL; } static int wrap_putenv (void *data, const char *k, const char *v) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; ap_table_set (wrap->r->subprocess_env, k, v); return 0; } static char *wrap_iterenv (void *data, int x, char **k, char **v) { WRAPPER_DATA *wrap = (WRAPPER_DATA *)data; array_header *env = ap_table_elts(wrap->r->subprocess_env); table_entry *entry = (table_entry*)env->elts; if (x >= env->nelts) return 0; if (entry[x].key == NULL || entry[x].val == NULL) return 0; *k = strdup(entry[x].key); *v = strdup(entry[x].val); return 0; } /************************************************************************* * Actual mod_ecs data structures for configuration */ typedef void (*InitFunc)(); typedef void (*CleanupFunc)(); typedef int (*CGIMainFunc)(int,char**,char**); typedef int (*WrapInitFunc)(void *,void *,void*,void*,void*,void*,void*); typedef struct { const char *libpath; ap_os_dso_handle_t dlib; } ecs_deplibs; typedef struct { const char *libpath; ap_os_dso_handle_t dlib; WrapInitFunc wrap_init; CGIMainFunc start; time_t mtime; int loaded; } ecs_manager; typedef struct { array_header *deplibs; array_header *handlers; int fork_enabled; int reload_enabled; } ecs_server_conf; const char *ECSInit = "ECSInit"; const char *ECSCleanUp = "ECSCleanup"; const char *WrapInit = "cgiwrap_init_emu"; const char *CGIMain = "main"; static void dummy (ap_os_dso_handle_t dlhandle) { } static void slib_cleanup (ap_os_dso_handle_t dlhandle) { CleanupFunc cleanupFunc; if ((cleanupFunc = (CleanupFunc)ap_os_dso_sym(dlhandle, ECSCleanUp))) { (*cleanupFunc)(); } ap_os_dso_unload(dlhandle); #ifdef ECS_DEBUG fprintf(stderr, "Unloading handle %d", dlhandle); #endif } void *create_ecs_config (pool *p, server_rec *dummy) { ecs_server_conf *new = ap_palloc (p, sizeof(ecs_server_conf)); new->deplibs = ap_make_array(p,1,sizeof(ecs_deplibs)); new->handlers = ap_make_array(p,1,sizeof(ecs_manager)); new->fork_enabled = 0; new->reload_enabled = 0; return (void *) new; } char** e_setup_cgi_env (request_rec* r) { char** env; ap_add_common_vars(r); ap_add_cgi_vars(r); env = ap_create_environment(r->pool,r->subprocess_env); return env; } const char *set_dep_lib (cmd_parms *parms, void *dummy, char *arg) { ecs_server_conf *cls = ap_get_module_config (parms->server->module_config, &ecs_module); ecs_deplibs *entry; ap_os_dso_handle_t dlhandle; InitFunc init_func; if ((dlhandle = ap_os_dso_load(arg)) == NULL) { return ap_os_dso_error(); } if ((init_func = (InitFunc)ap_os_dso_sym(dlhandle, ECSInit))) { (*init_func)(); } ap_register_cleanup (cls->deplibs->pool, dlhandle, slib_cleanup, slib_cleanup); entry = (ecs_deplibs*)ap_push_array(cls->deplibs); entry->libpath = ap_pstrdup(cls->deplibs->pool, arg); entry->dlib = dlhandle; return NULL; } /* Load an ecs shared library */ static const char *load_library (ap_pool *p, ecs_manager *entry, int do_stat, char *prefix) { ap_os_dso_handle_t dlhandle; InitFunc init_func; CGIMainFunc cgi_main; WrapInitFunc wrap_init; char *err; struct stat s; if (do_stat) { if (stat(entry->libpath, &s) == -1) { err = ap_psprintf (p, "Failed to stat library file %s: %d", entry->libpath, errno); return err; } entry->mtime = s.st_mtime; } if (entry->loaded == 1) { fprintf (stderr, "Warning: attempting to reload %s but it's already loaded\n", entry->libpath); } /* This does a RTLD_NOW, if we want lazy, we're going to have to do it * ourselves */ if ((dlhandle = ap_os_dso_load(entry->libpath)) == NULL) { return ap_os_dso_error(); } if (entry->dlib == dlhandle) { fprintf (stderr, "Warning: Reload of %s returned same handle\n", entry->libpath); } if ((init_func = (InitFunc)ap_os_dso_sym(dlhandle, ECSInit))) { (*init_func)(); } if (!(wrap_init = (WrapInitFunc)ap_os_dso_sym(dlhandle, WrapInit))) { err = ap_psprintf (p, "Failed to find wrap init function %s in shared object: %s", WrapInit, dlerror()); ap_os_dso_unload(dlhandle); return err; } if (!(cgi_main = (CGIMainFunc)ap_os_dso_sym(dlhandle, CGIMain))) { err = ap_psprintf (p, "Failed to find entry function %s in shared object: %s", CGIMain, dlerror()); ap_os_dso_unload(dlhandle); return err; } /* Um, this may be a problem... */ ap_register_cleanup (p, dlhandle, slib_cleanup, dummy); entry->dlib = dlhandle; entry->wrap_init = wrap_init; entry->start = cgi_main; entry->loaded = 1; fprintf (stderr, "%sLoaded library %s [%d]\n", prefix, entry->libpath, dlhandle); return NULL; } const char *set_pre_lib (cmd_parms *parms, void *dummy, char *arg) { ecs_server_conf *cls = ap_get_module_config (parms->server->module_config, &ecs_module); ecs_manager *entry; entry = (ecs_manager*)ap_push_array(cls->handlers); entry->libpath = ap_pstrdup(cls->handlers->pool, arg); return load_library (cls->handlers->pool, entry, 1, "Pre"); } const char *set_fork (cmd_parms *parms, void *dummy, int flag) { ecs_server_conf *cls = ap_get_module_config (parms->server->module_config, &ecs_module); cls->fork_enabled = (flag ? 1 : 0); return NULL; } const char *set_reload (cmd_parms *parms, void *dummy, int flag) { ecs_server_conf *cls = ap_get_module_config (parms->server->module_config, &ecs_module); cls->reload_enabled = (flag ? 1 : 0); return NULL; } static ecs_manager *findHandler(array_header *a, char *file) { ecs_manager *list = (ecs_manager*)(a->elts); int i; for (i = 0; i < a->nelts; i++) { if (!strcmp(list[i].libpath, file)) return &(list[i]); } return NULL; } static int run_dl_cgi (ecs_server_conf *sconf, request_rec* r, char* argv0) { int ret = 0; void* handle; int cgi_status; int argc; char** argv; WRAPPER_DATA *wdata; ecs_manager *handler; const char *err; char** envp = e_setup_cgi_env(r); /* Find/open library */ handler = findHandler (sconf->handlers, r->filename); if (handler == NULL) { ecs_manager my_handler; my_handler.libpath = ap_pstrdup(sconf->handlers->pool, r->filename); err = load_library(sconf->handlers->pool, &my_handler, 1, ""); if (err != NULL) { log_reason("Error opening library:", err, r); ret = ERROR; } else { handler = (ecs_manager*)ap_push_array(sconf->handlers); handler->dlib = my_handler.dlib; handler->wrap_init = my_handler.wrap_init; handler->start = my_handler.start; handler->mtime = my_handler.mtime; handler->loaded = my_handler.loaded; handler->libpath = my_handler.libpath; } } else if (sconf->reload_enabled) { struct stat s; if (stat(handler->libpath, &s) == -1) { log_reason("Unable to stat file: ", handler->libpath, r); ret = ERROR; } else if (!handler->loaded || (s.st_mtime > handler->mtime)) { if (handler->loaded) { int x; fprintf (stderr, "Unloading %s\n", handler->libpath); slib_cleanup(handler->dlib); /* Really unload this thing */ while ((x < 100) && (dlclose(handler->dlib) != -1)) x++; if (x == 100) fprintf (stderr, "dlclose() never returned -1"); handler->loaded = 0; } err = load_library(sconf->handlers->pool, handler, 0, "Re"); if (err != NULL) { log_reason("Error opening library:", err, r); ret = ERROR; } handler->mtime = s.st_mtime; } } if (!ret) { if ((!r->args) || (!r->args[0]) || (ap_ind(r->args,'=') >= 0) ) { argc = 1; argv = &argv0; } else { argv = ecs_create_argv(r->pool, NULL,NULL,NULL,argv0,r->args); for (argc = 0 ; argv[argc] ; ++argc); } } /* Yow ... at last we can go ... Now, what to do if CGI crashes (aaargh) Methinks an atexit ... cleanup perhaps; have to figgerout what the atexit needs to invoke ... yuk! Or maybe better to catch SIGSEGV and SIGBUS ? - we don't want coredumps from someone else's bugs, do we? still doesn't guarantee anything very good :-( Ugh .. nothing better??? */ if (!ret) { wdata = (WRAPPER_DATA *) ap_pcalloc (r->pool, sizeof (WRAPPER_DATA)); /* We use malloc here because there is no pool alloc command for * realloc... */ wdata->hbuf.buf = (char *) malloc (sizeof(char) * 1024); wdata->hbuf.max = 1024; wdata->r = r; #ifdef ECS_DEBUG fprintf (stderr, "wrap_init()\n"); #endif handler->wrap_init(wdata, wrap_read, wrap_vprintf, wrap_write, wrap_getenv, wrap_putenv, wrap_iterenv); #ifdef ECS_DEBUG fprintf (stderr, "cgi_main()\n"); #endif cgi_status = handler->start(argc,argv,envp); if (cgi_status != 0) { /*log_reason("CGI returned error status", cgi_status, r) ;*/ ret = ERROR; } if (wdata->returns != OK) ret = wdata->returns; free (wdata->hbuf.buf); } return ret; } int run_xcgi (ecs_server_conf *conf, request_rec* r, char* argv0) { int len_read; char argsbuffer[HUGE_STRING_LEN]; int ret = 0; ret = run_dl_cgi (conf, r, argv0); if (ret == INTERNAL_REDIRECT) { const char* location = ap_table_get (r->headers_out, "Location"); /* This redirect needs to be a GET no matter what the original * method was. */ r->method = ap_pstrdup(r->pool, "GET"); r->method_number = M_GET; /* We already read the message body (if any), so don't allow * the redirected request to think it has one. We can ignore * Transfer-Encoding, since we used REQUEST_CHUNKED_ERROR. */ ap_table_unset(r->headers_in, "Content-Length"); ap_internal_redirect_handler (location, r); return OK; } return ret; } int ecs_handler (request_rec* r) { int retval; char *argv0; int is_included = !strcmp (r->protocol, "INCLUDED"); void *sconf = r->server->module_config; ecs_server_conf *conf = (ecs_server_conf *)ap_get_module_config(sconf, &ecs_module); ap_error_log2stderr(r->server); #ifdef ECS_DEBUG fprintf(stderr, "running ecs_handler %s\n", r->filename); #endif if((argv0 = strrchr(r->filename,'/')) != NULL) argv0++; else argv0 = r->filename; if (!(ap_allow_options (r) & OPT_EXECCGI) ) return log_scripterror(r, conf, FORBIDDEN, "Options ExecCGI is off in this directory"); if (S_ISDIR(r->finfo.st_mode)) return log_scripterror(r, conf, FORBIDDEN, "attempt to invoke directory as script"); if (r->finfo.st_mode == 0) return log_scripterror(r, conf, NOT_FOUND, "file not found or unable to stat"); #ifdef ECS_DEBUG fprintf (stderr, "ap_setup_client_block\n"); #endif if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) return retval; #ifdef ECS_DEBUG fprintf (stderr, "before run\n"); #endif return run_xcgi(conf, r, argv0); } handler_rec ecs_handlers[] = { { ECS_MAGIC_TYPE, ecs_handler }, { "ecs-cgi", ecs_handler}, { NULL } }; command_rec ecs_cmds[] = { { "ECSFork", set_fork, NULL, OR_FILEINFO, FLAG, "On or off to enable or disable (default) forking before calling cgi_main" }, { "ECSReload", set_reload, NULL, OR_FILEINFO, FLAG, "On or off to enable or disable (default) checking if the shared library\n" \ " has changed and reloading it if it has"}, { "ECSDepLib", set_dep_lib, NULL, RSRC_CONF, TAKE1, "The location of a dependent lib to dlopen during init"}, { "ECSPreload", set_pre_lib, NULL, RSRC_CONF, TAKE1, "The location of a shared lib handler to preload during init"}, { NULL } }; module ecs_module = { STANDARD_MODULE_STUFF, NULL, /* initializer */ NULL, /* dir config creater */ NULL, /* dir merger --- default is to override */ create_ecs_config, /* server config */ NULL, /*merge_ecs_config,*/ /* merge server config */ ecs_cmds, /* command table */ ecs_handlers, /* handlers */ NULL, /* filename translation */ NULL, /* check_user_id */ NULL, /* check auth */ NULL, /* check access */ NULL, /* type_checker */ NULL, /* fixups */ NULL, /* logger */ #if MODULE_MAGIC_NUMBER >= 19970103 NULL, /* [3] header parser */ #endif #if MODULE_MAGIC_NUMBER >= 19970719 NULL, /* process initializer */ #endif #if MODULE_MAGIC_NUMBER >= 19970728 NULL, /* process exit/cleanup */ #endif #if MODULE_MAGIC_NUMBER >= 19970902 NULL, /* [1] post read_request handling */ #endif }; /* Here's some stuff that essentially duplicates util_script.c This really should be merged, but if _I_ do that it'll break modularity and leave users with a nasty versioning problem. If I get a round tuit sometime, I might ask the Apache folks about integrating some changes in the main source tree. */ /* If a request includes query info in the URL (stuff after "?"), and * the query info does not contain "=" (indicative of a FORM submission), * then this routine is called to create the argument list to be passed * to the CGI script. When suexec is enabled, the suexec path, user, and * group are the first three arguments to be passed; if not, all three * must be NULL. The query info is split into separate arguments, where * "+" is the separator between keyword arguments. */ char **ecs_create_argv(pool *p, char *path, char *user, char *group, char *av0, const char *args) { int x, numwords; char **av; char *w; int idx = 0; /* count the number of keywords */ for (x = 0, numwords = 1; args[x]; x++) if (args[x] == '+') ++numwords; if (numwords > APACHE_ARG_MAX - 5) { numwords = APACHE_ARG_MAX - 5; /* Truncate args to prevent overrun */ } av = (char **)ap_palloc(p, (numwords + 5) * sizeof(char *)); if (path) av[idx++] = path; if (user) av[idx++] = user; if (group) av[idx++] = group; av[idx++] = av0; for (x = 1; x <= numwords; x++) { w = ap_getword_nulls(p, &args, '+'); ap_unescape_url(w); av[idx++] = ap_escape_shell_cmd(p, w); } av[idx] = NULL; return av; } clearsilver-0.10.5/mod_ecs/mod_ecs.h0000644001211700116100000000115310261037512014214 00000000000000#ifndef __MOD_ECS_H_ #define __MOD_ECS_H_ 1 /* not a real .h file - just for the cgiplusplus interface */ /* not an enum - want a bitfield */ #define APACHE_CGI 0x1000 /* need nonzero even for a default :-) */ #define CGIPLUSPLUS 1 #define EXTENDED_CGI 2 #define USE_STRICT 4 #define OPTIMISED_DESCRIPTORS 8 #define ENV_AS_TABLE 0x10 #define USE_CGI_STDERR 0x20 #define STDERR_TO_HTML 0x40 #define NPH 0x100 #define STDIN_BUF 0x200 #define OWN_STDOUT 0x400 #define OWN_STDERR 0x800 /* one day we'll get round to implementing all the above */ #define ECS_MAGIC_TYPE "application/x-ecs-cgi" #endif /* __MOD_ECS_H_ */ clearsilver-0.10.5/imd/0000755001211700116100000000000010645505045011661 500000000000000clearsilver-0.10.5/imd/0.gif0000644001211700116100000000006210261037511012415 00000000000000GIF89a‘ÿÿÿ!ù ,clearsilver-0.10.5/imd/1.gif0000644001211700116100000000006210261037511012416 00000000000000GIF89a‘ÿÿÿ!ù ,clearsilver-0.10.5/imd/2.gif0000644001211700116100000000006210261037511012417 00000000000000GIF89a‘ÿÿÿ!ù ,clearsilver-0.10.5/imd/3.gif0000644001211700116100000000006210261037511012420 00000000000000GIF89a‘ÿÿÿ!ù ,clearsilver-0.10.5/imd/4.gif0000644001211700116100000000224510261037511012426 00000000000000GIF89awæ+++<<<===LLLNNN\\\]]]```jjjmmmrrrxxxyyy}}}ƒƒƒ………ˆˆˆ’’’“““–––———žžž   ¦¦¦§§§©©©ªªª®®®³³³µµµ¶¶¶¹¹¹¼¼¼½½½¾¾¾ÃÃÃÄÄÄÆÆÆÉÉÉËËËÏÏÏÐÐÐÓÓÓÔÔÔ×××ØØØÙÙÙÛÛÛÜÜÜÞÞÞßßßàààâââãããäääçççèèèêêêìììîîîïïïðððñññòòòóóóôôôõõõööö÷÷÷øøøùùùúúúûûûüüüýýýþþþÿÿÿ!ù N,wþH°àÀ>€B¤ˆ$I–01(ƒ† 9vðð„È‘$M ¦PÁÂE 7rlbdIÁ$L PÑ ;~QRPC‡"J XábA¬p!C$N¨pAC‡#H°€ƒ‡'VÀ¸Á£HÁ"P¸°Á -jì0K‚&\ࢄŠ9†,p 0tâ!0 A >˜`aHÁPà@Â…$VÐøQ@€,xPACˆ2z´~{víÛ¹wÖMÛ6nÝ]÷m]ývòâÁ·÷¾ž{y'çåw7ÿý~üýÙŸ÷åGà€º‡Þ|üÕŸ‚úàƒô½—^… þg`‚Fˆ … ZÈ €^b†–8↠’(¢†šè"ŠÊÈ¢1®˜#Œ*òøbŠ?Ö¨c@ÒáGrx¢‡I¶xãA6‰#‘Búhd‡Hb©äŒLjéäŽEv¹d–cnù¤•brI¦šf‚Ye˜kž g›TJ å•e~Y§—SFÉçiÊùæ v¢§›…Ω§Ÿyö‰'›‹>*h¢„þi(ŒBêh ˆZªè¦‡îÙ( ¡f:©§•Žzi¤œŠª)©ÿ˜JÚ©ªŸÂÊj©²ºz*­©¾º*¨±¶jꬾÖú«­ÀÞ,®Âæ:¬®ÄîZl¯ÒVíµÐfûì¶ÎvÛì·Ì†»ì¸Ê–›ì¹È¦{ìºÆ¶K-¶Ü‚K.ºì¾«­·âš«®»”ö‹ª¿¼<­ÀÖÞ+¯¾õ /¾óîko¼ùÒËï¿\ñÀ qà g¼ðÁ?Ì0Â[l2Æ'k']ôÔ7ËÌrÖO­tÓ\WÍ4ÖQk 5ÑRo]v×V§}ö×d£m¶×W«-7ÛcÛ ·Þu;clearsilver-0.10.5/imd/5.gif0000644001211700116100000000006210261037511012422 00000000000000GIF89a‘ÿÿÿ!ù ,clearsilver-0.10.5/imd/6.gif0000644001211700116100000000222310261037511012424 00000000000000GIF89aÂæ+++<<<===LLLNNN\\\]]]```jjjmmmrrrxxxyyy}}}ƒƒƒ………ˆˆˆ’’’“““–––———žžž   ¦¦¦§§§©©©ªªª®®®³³³µµµ¶¶¶¹¹¹¼¼¼½½½¾¾¾ÃÃÃÄÄÄÆÆÆÉÉÉËËËÏÏÏÐÐÐÓÓÓÔÔÔ×××ØØØÙÙÙÛÛÛÜÜÜÞÞÞßßßàààâââãããäääçççèèèêêêìììîîîïïïðððñññòòòóóóôôôõõõööö÷÷÷øøøùùùúúúûûûüüüýýýþþþÿÿÿ!ù N,Âþô‘"„†  (0 €‡#JœH±¢Å‹3jÜȱ£Ç CŠI²¤É“(Sª|èä$:\à@ÁèÜɳ§ÏŸ@ƒ J´¨Ñ£H“*]Ê´©Ó§P£JJµªN'@l°0ñ!ƒ…  0 ¬Ù³hÓª]˶­Û·pãÊK·®Ý»xóêÝË·¯ß¿€Ë:‚ã 0P€À Á#KžL¹²å˘3kÞ̹³çÏ C‹Mº´éÓ¨S«^ ÙÉ1T”Áá  ØÍ»·ïßÀƒ N¼¸ñãÈ“+_μ¹óçУKŸN½ºõÝNŠì¨Ñ .þPˆà`ùóèÓ«_Ͼ½û÷ðãËŸO¿¾ýûøóëßÏ¿¿ÿÿh^v<Üà 'ŒàX ÁF(á„Vhá…f¨á†vèᇠ†(âˆ$–hâ‰(¦¨âŠ:q„:Ðà‚ 'B\PÁŽ<öèã@)äDiä‘H&©ä’L6éä“PF)å”TViåŽN 8Ìà (” Âh`æ™h¦©æšl¶éæ›pÆ)çœtÖiçxæ©çž|öé矀j¦JñÃ8ÐC * ` !D*餔Vj饘fªé¦œvêé§ †*ꨤ–jꩨ¦ªêª¬FêÄòF á9Ü@C .° B ¼öêë¯À+ì°Äkì±È&«ì²Ì6ëì³ÐF+í´ÔVkíµ¼:ÑDGĬ;䀃 4È`î¹è¦«îºì¶ëî»ðÆ+ï¼ôÖkï½øæ«ï¾üöëï¿l®N0±DHQC„=D,ñÄWlñÅg¬ñÆwìñÇ ‡,òÈ$—lòÉ(§¬òÊ,GLðË0Ç,óÌ4×lóÍ8ç¬óÎ<÷ìóÏ@-ôÐDmôÑH'­ôÒL7íôÓPG-õÔTWmõÕXg­õÖ\wíõ×`‡-öØd—möÙh§­öÚl·í6Õ;clearsilver-0.10.5/imd/7.gif0000644001211700116100000000120010261037511012417 00000000000000GIF89aæ+++<<<===LLLNNN\\\]]]```jjjmmmrrrxxxyyy}}}ƒƒƒ………ˆˆˆ’’’“““–––———žžž   ¦¦¦§§§©©©ªªª®®®³³³µµµ¶¶¶¹¹¹¼¼¼½½½¾¾¾ÃÃÃÄÄÄÆÆÆÉÉÉËËËÏÏÏÐÐÐÓÓÓÔÔÔ×××ØØØÙÙÙÛÛÛÜÜÜÞÞÞßßßàààâââãããäääçççèèèêêêìììîîîïïïðððñññòòòóóóôôôõõõööö÷÷÷øøøùùùúúúûûûüüüýýýþþþÿÿÿ!ù N,ÝPÁ‚4„H!£‡“‡ p@ :XAãćHÐ ‚… L°°䣓0€@C(^àâ‚&\ࢄŠ9†¸\à … <@ѢƎ".H°€ƒ‡'VÀ¸ÁëÇ 2tAâ„ 4tø8âRC‡"J XábA¸ A -`ÐÀ±ã%.S¨`á"9xøbd‰K4làȱCs"G’4qÙà Cˆ1‚$É&.sëÞÍ»·ïßÀƒ; ;clearsilver-0.10.5/imd/Makefile0000644001211700116100000000072510344021537013240 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk IMD_EXE = imd.cgi IMD_SRC = imd.c IMD_OBJ = $(IMD_SRC:%.c=%.o) CFLAGS += -I/usr/local/include DLIBS += -lneo_cgi -lneo_cs -lneo_utl # -lefence LIBS += -L$(LIB_DIR) $(DLIBS) -L/usr/local/lib -lgd -ljpeg -lz TARGETS = $(IMD_EXE) all: $(TARGETS) $(IMD_EXE): $(IMD_OBJ) $(DEP_LIBS) $(LD) $@ $(IMD_OBJ) $(LIBS) clean: $(RM) *.o distclean: $(RM) Makefile.depends $(TARGETS) *.o clearsilver-0.10.5/imd/README0000644001211700116100000000103310261037511012446 00000000000000 To set up imd, you need to add the following directives to an apache conf file. If you have sufficient permissions, you can add these to the .htaccess files for an image directory: AddHandler cgi-script .cgi AddHandler imd-handler .imd Action imd-handler /url/path/to/imd.cgi Then, copy example.imd to somewhere in your URL space, and modify the settings in there. You will probably need to modify Template to point to the installed location of the imd.cs file. You can personalize the imd.cs file to personalize your image server. clearsilver-0.10.5/imd/example.imd0000644001211700116100000000114710261037511013722 00000000000000# Location of the image albums (an album is a directory of images # so this is a directory of directories of imaages) BASEDIR = /home/blong/images # Full Path to the CS template file used for display Template=/home/blong/public_html/Images/imd.cs # Scaling sizes. imd will scale the image to be at or below this size # Thumb is for the thumbnails, and Picture is for individual pictures ThumbWidth = 120 ThumbHeight = 90 PictureWidth = 600 PictureHeight = 450 # Number of thumbnails to show per page PerPage = 50 # Assumed browser width for album show PageWidth = 640 # Image Server Title Title = My Pictures clearsilver-0.10.5/imd/imd.c0000644001211700116100000006765010522672250012531 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ /* Bring in gd library functions */ #include "gd.h" /* Bring in standard I/O so we can output the PNG to a file */ #include #include #include #include #include #include #include #include #include #include #include "ClearSilver.h" /* from httpd util.c : made infamous with Roy owes Rob beer. */ static char *months[] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; int find_month(char *mon) { register int x; for(x=0;x<12;x++) if(!strcmp(months[x],mon)) return x; return -1; } int later_than(struct tm *lms, char *ims) { char *ip; char mname[256]; int year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0, x; /* Whatever format we're looking at, it will start * with weekday. */ /* Skip to first space. */ if(!(ip = strchr(ims,' '))) return 0; else while(isspace(*ip)) ++ip; if(isalpha(*ip)) { /* ctime */ sscanf(ip,"%25s %d %d:%d:%d %d",mname,&day,&hour,&min,&sec,&year); } else if(ip[2] == '-') { /* RFC 850 (normal HTTP) */ char t[256]; sscanf(ip,"%s %d:%d:%d",t,&hour,&min,&sec); t[2] = '\0'; day = atoi(t); t[6] = '\0'; strcpy(mname,&t[3]); x = atoi(&t[7]); /* Prevent wraparound from ambiguity */ if(x < 70) x += 100; year = 1900 + x; } else { /* RFC 822 */ sscanf(ip,"%d %s %d %d:%d:%d",&day,mname,&year,&hour,&min,&sec); } month = find_month(mname); if((x = (1900+lms->tm_year) - year)) return x < 0; if((x = lms->tm_mon - month)) return x < 0; if((x = lms->tm_mday - day)) return x < 0; if((x = lms->tm_hour - hour)) return x < 0; if((x = lms->tm_min - min)) return x < 0; if((x = lms->tm_sec - sec)) return x < 0; return 1; } int gif_size (char *file, int *width, int *height) { UINT8 data[256]; int fd; int blen; *width = 0; *height = 0; fd = open (file, O_RDONLY); if (fd == -1) return -1; blen = read(fd, data, sizeof(data)); close(fd); if (blen < 10) return -1; if (strncmp(data, "GIF87a", 6) && strncmp(data, "GIF89a", 6)) return -1; *width = data[6] + data[7]*256; *height = data[8] + data[9]*256; return 0; } int jpeg_size (char *file, int *width, int *height) { UINT8 data[64*1024]; int blen; int fd; int pos; int length; UINT8 tag, marker; *width = 0; *height = 0; fd = open (file, O_RDONLY); if (fd == -1) return -1; blen = read(fd, data, sizeof(data)); close(fd); pos = 2; while (pos+8 < blen) { tag = data[pos+0]; if (tag != 0xff) return -1; marker = data[pos+1]; length = data[pos+2] * 256 + data[pos+3] + 2; if (marker >= 0xc0 && marker <= 0xcf && marker != 0xc4 && marker != 0xc8 && marker != 0xcc) { *height = data[pos+5] * 256 + data[pos+6]; *width = data[pos+7] * 256 + data[pos+8]; ne_warn("%s: %dx%d", file, *width, *height); return 0; } pos += length; } return -1; } int isdir(char *dir) { struct stat statinfo; if ( stat(dir, &statinfo) != 0) { return 0; } return S_ISDIR(statinfo.st_mode); } int create_directories(char *fullpath) { char s[4000]; char *last_slash; int last_slash_pos; if ((fullpath == NULL) || (strlen(fullpath) > 4000)) { return 1; } last_slash = strrchr(fullpath,'/'); last_slash_pos = (last_slash - fullpath); /* fprintf(stderr,"dira(%d): %s\n", last_slash_pos,fullpath); */ if (last_slash_pos > 2) { strncpy(s,fullpath,last_slash_pos); s[last_slash_pos] = 0; /* fprintf(stderr,"dir: %s\n", s); */ if (!isdir(s)) { char s2[4000]; sprintf(s2,"mkdir -p %s", s); return system(s2); } } else { return 1; } return 0; } NEOERR *rotate_image(char *path, char *file, int degree, char *rpath) { char cmd[256]; char nfile[_POSIX_PATH_MAX]; char ofile[_POSIX_PATH_MAX]; char *ch, *opt; int is_jpeg = 0; struct stat s; int r; snprintf (ofile, sizeof(ofile), "%s/%s", path, file); snprintf (rpath, _POSIX_PATH_MAX, "%s/%s", path, file); ch = strrchr(rpath, '.'); if ((!strcasecmp(ch, ".jpg")) || (!strcasecmp(ch, ".jpeg")) || (!strcasecmp(ch, ".thm"))) { is_jpeg = 1; } else if (strcasecmp(ch, ".gif")) { return nerr_raise(NERR_ASSERT, "Only support gif/jpeg for rotation, ext %s", ch); } *ch = '\0'; if (degree == 90) { strcat(rpath, "_r"); opt = "-cw"; } else if (degree == -90) { strcat(rpath, "_l"); opt = "-ccw"; } else if (degree == 180) { strcat(rpath, "_u"); opt = "-rotate180"; } else { return nerr_raise(NERR_ASSERT, "currently only support 90/-90/180 rotations"); } if (is_jpeg) { strcat(rpath, ".jpg"); snprintf(cmd, sizeof(cmd), "djpeg -pnm %s | pnmflip %s | cjpeg -quality 85 > %s", ofile, opt, rpath); } else { strcat(rpath, ".gif"); snprintf(cmd, sizeof(cmd), "giftopnm %s | pnmflip %s | ppmtogif > %s", ofile, opt, rpath); } /* already exists? */ if (!stat(rpath, &s)) { return STATUS_OK; } r = system(cmd); if (r) return nerr_raise_errno (NERR_SYSTEM, "%s returned %d", cmd, r); /* always save off the old file */ snprintf (nfile, sizeof(nfile), "%s/%s.orig", path, file); if (stat(nfile, &s)) { if (link(ofile, nfile)) return nerr_raise_errno (NERR_SYSTEM, "Unable to link %s -> %s", ofile, nfile); unlink(ofile); } return STATUS_OK; } NEOERR *scale_and_display_image(char *fname,int maxW,int maxH,char *cachepath, int quality) { NEOERR *err = STATUS_OK; /* Declare the image */ gdImagePtr src_im = 0; /* Declare input file */ FILE *infile=0, *cachefile=0; int srcX,srcY,srcW,srcH; FILE *dispfile=0; struct stat s; /* if we can open the cachepath, then just print it */ if (!stat(cachepath, &s) && s.st_size) cachefile = fopen(cachepath,"rb"); if (cachefile) { /* we should probably stat the files and make sure the thumbnail is current */ /* fprintf(stderr,"using cachefile: %s\n",cachepath); */ dispfile = cachefile; } else { char cmd[1024]; int factor=1; int l; int is_jpeg = 0, is_gif = 0; l = strlen(fname); if ((l>4 && !strcasecmp(fname+l-4, ".jpg")) || (l>4 && !strcasecmp(fname+l-4, ".thm")) || (l>5 && !strcasecmp(fname+l-5, ".jpeg"))) is_jpeg = 1; else if (l>4 && !strcasecmp(fname+l-4, ".gif")) is_gif = 1; if (is_jpeg) { if (!quality) { if (!jpeg_size (fname, &srcW, &srcH)) { if ((srcW > maxW) || (srcH > maxH)) { factor = 2; if (srcW / factor > maxW) { factor = 4; if (srcW / factor > maxW) factor = 8; } } } /* ne_warn("factor %d\n", factor); */ snprintf (cmd, sizeof(cmd), "/usr/bin/djpeg -fast -scale 1/%d '%s' | /usr/bin/cjpeg -quality 60 -progressive -dct fast -outfile '%s'", factor, fname, cachepath); create_directories(cachepath); system(cmd); if (!stat(cachepath, &s) && s.st_size) cachefile = fopen(cachepath,"rb"); else ne_warn("external command failed to create file\n"); } if (cachefile) { dispfile = cachefile; } else /* no cachefile */ { /* fprintf(stderr,"reading image\n"); */ /* Read the image in */ infile = fopen(fname,"rb"); src_im = gdImageCreateFromJpeg(infile); srcX=0; srcY=0; srcW=src_im->sx; srcH=src_im->sy; /* figure out if we need to scale it */ if ((maxW && srcW > maxW) || (maxH && srcH > maxH)) { /* scale paramaters */ int dstX,dstY,dstW,dstH; /* Declare output file */ FILE *jpegout; gdImagePtr dest_im; float srcAspect,dstAspect; /* create the destination image */ dstX=0; dstY=0; srcAspect = ((float)srcW/(float)srcH); dstAspect = ((float)maxW/(float)maxH); if (srcAspect == dstAspect) { /* they are the same aspect ratio */ dstW = maxW; dstH = maxH; } else if ( srcAspect > dstAspect ) { /* if the src image has wider aspect ratio than the max */ dstW = maxW; dstH = (int) ( ((float)dstW/(float)srcW) * srcH ); } else { /* if the src image has taller aspect ratio than the max */ dstH = maxW; dstW = (int) ( ((float)dstH/(float)srcH) * srcW ); } #ifdef GD2_VERS dest_im = gdImageCreateTrueColor(dstW,dstH); #else dest_im = gdImageCreate(dstW,dstH); #endif /* fprintf(stderr,"scaling to (%d,%d)\n",dstW,dstH); */ /* Scale it to the destination image */ gdImageCopyResized(dest_im,src_im,dstX,dstY,srcX,srcY,dstW,dstH,srcW,srcH); /* fprintf(stderr,"scaling finished\n"); */ /* write the output image */ create_directories(cachepath); jpegout = fopen(cachepath,"wb+"); if (!jpegout) { jpegout = fopen("/tmp/foobar.jpg","wb+"); } if (jpegout) { gdImageJpeg(dest_im,jpegout,-1); fflush(jpegout); /* now print that data out the stream */ dispfile = jpegout; } else { return nerr_raise_errno(NERR_IO, "Unable to create output file: %s", cachepath); } gdImageDestroy(dest_im); } else { /* just print the input file because it's small enough */ dispfile = infile; } } } else if (is_gif) { float scale = 1.0; if (!gif_size (fname, &srcW, &srcH)) { if ((srcW > maxW) || (srcH > maxH)) { scale = 0.5; if (srcW * scale > maxW) { scale = 0.25; if (srcW * scale > maxW) factor = 0.125; } } } if (scale < 1.0) { snprintf (cmd, sizeof(cmd), "/usr/bin/giftopnm '%s' | /usr/bin/pnmscale %5.3f | ppmquant 256 | ppmtogif > '%s'", fname, scale, cachepath); create_directories(cachepath); system(cmd); dispfile = fopen(cachepath,"rb"); if (dispfile == NULL) return nerr_raise_errno(NERR_IO, "Unable to open file: %s", cachepath); } else { dispfile = fopen(fname, "rb"); if (dispfile == NULL) return nerr_raise_errno(NERR_IO, "Unable to open file: %s", fname); } } else { dispfile = fopen(fname,"rb"); } } /* the data in "dispfile" is going to be printed now */ { char buf[8192]; int count; if (!fstat(fileno(dispfile), &s) && s.st_size) { cgiwrap_writef("Content-Length: %ld\n\n", s.st_size); } else { cgiwrap_writef("\n"); } fseek(dispfile,0,SEEK_SET); do { count = fread(buf,1,sizeof(buf),dispfile); if (count > 0) { err = cgiwrap_write(buf,count); } } while (count > 0); } if (dispfile) fclose(dispfile); if (src_im) gdImageDestroy(src_im); return nerr_pass(err); } NEOERR *load_images (char *path, ULIST **rfiles, char *partial, int descend) { NEOERR *err = STATUS_OK; DIR *dp; struct dirent *de; int is_jpeg, is_gif, l; char fpath[_POSIX_PATH_MAX]; char ppath[_POSIX_PATH_MAX]; ULIST *files = NULL; if ((dp = opendir (path)) == NULL) { return nerr_raise(NERR_IO, "Unable to opendir %s: [%d] %s", path, errno, strerror(errno)); } if (rfiles == NULL || *rfiles == NULL) { err = uListInit(&files, 50, 0); if (err) return nerr_pass(err); *rfiles = files; } else { files = *rfiles; } while ((de = readdir (dp)) != NULL) { if (de->d_name[0] != '.') { snprintf(fpath, sizeof(fpath), "%s/%s", path, de->d_name); if (partial) { snprintf(ppath, sizeof(ppath), "%s/%s", partial, de->d_name); } else { strncpy(ppath, de->d_name, sizeof(ppath)); } if (descend && isdir(fpath)) { err = load_images(fpath, rfiles, ppath, descend); if (err) break; } else { l = strlen(de->d_name); is_jpeg = 0; is_gif = 0; if ((l>4 && !strcasecmp(de->d_name+l-4, ".jpg")) || (l>4 && !strcasecmp(de->d_name+l-4, ".thm")) || (l>5 && !strcasecmp(de->d_name+l-5, ".jpeg"))) is_jpeg = 1; else if (l>4 && !strcasecmp(de->d_name+l-4, ".gif")) is_gif = 1; if (is_gif || is_jpeg) { err = uListAppend(files, strdup(ppath)); if (err) break; } } } } closedir(dp); if (err) { uListDestroy(&files, ULIST_FREE); } else { *rfiles = files; } return nerr_pass(err); } NEOERR *export_image(CGI *cgi, char *prefix, char *path, char *file) { NEOERR *err; char buf[256]; char num[20]; int i = 0; int r, l; int width, height; char ipath[_POSIX_PATH_MAX]; int is_jpeg = 0, is_gif = 0, is_thm = 0; l = strlen(file); if ((l>4 && !strcasecmp(file+l-4, ".jpg")) || (l>5 && !strcasecmp(file+l-5, ".jpeg"))) is_jpeg = 1; else if (l>4 && !strcasecmp(file+l-4, ".gif")) is_gif = 1; else if (l>4 && !strcasecmp(file+l-4, ".thm")) is_thm = 1; snprintf (buf, sizeof(buf), "%s.%d", prefix, i); err = hdf_set_value (cgi->hdf, prefix, file); if (err != STATUS_OK) return nerr_pass(err); snprintf (ipath, sizeof(ipath), "%s/%s", path, file); if (is_jpeg || is_thm) r = jpeg_size(ipath, &width, &height); else r = gif_size(ipath, &width, &height); if (!r) { snprintf (buf, sizeof(buf), "%s.width", prefix); snprintf (num, sizeof(num), "%d", width); err = hdf_set_value (cgi->hdf, buf, num); if (err != STATUS_OK) return nerr_pass(err); snprintf (buf, sizeof(buf), "%s.height", prefix); snprintf (num, sizeof(num), "%d", height); err = hdf_set_value (cgi->hdf, buf, num); if (err != STATUS_OK) return nerr_pass(err); } if (is_thm) { strcpy(ipath, file); strcpy(ipath+l-4, ".avi"); snprintf(buf, sizeof(buf), "%s.avi", prefix); err = hdf_set_value (cgi->hdf, buf, ipath); if (err != STATUS_OK) return nerr_pass(err); } return STATUS_OK; } NEOERR *scale_images (CGI *cgi, char *prefix, int width, int height, int force) { NEOERR *err; char num[20]; HDF *obj; int i, x; int factor; obj = hdf_get_obj (cgi->hdf, prefix); if (obj) obj = hdf_obj_child (obj); while (obj) { factor = 1; i = hdf_get_int_value(obj, "height", -1); if (i != -1) { x = i; while (x > height) { /* factor = factor * 2;*/ factor++; x = i / factor; } snprintf (num, sizeof(num), "%d", x); err = hdf_set_value (obj, "height", num); if (err != STATUS_OK) return nerr_pass (err); i = hdf_get_int_value(obj, "width", -1); if (i != -1) { i = i / factor; snprintf (num, sizeof(num), "%d", i); err = hdf_set_value (obj, "width", num); if (err != STATUS_OK) return nerr_pass (err); } } else { snprintf (num, sizeof(num), "%d", height); err = hdf_set_value (obj, "height", num); if (err != STATUS_OK) return nerr_pass (err); snprintf (num, sizeof(num), "%d", width); err = hdf_set_value (obj, "width", num); if (err != STATUS_OK) return nerr_pass (err); } obj = hdf_obj_next(obj); } return STATUS_OK; } int alpha_sort(const void *a, const void *b) { char **sa = (char **)a; char **sb = (char **)b; /* ne_warn("%s %s: %d", *sa, *sb, strcmp(*sa, *sb)); */ return strcmp(*sa, *sb); } static NEOERR *export_album_path(CGI *cgi, char *album, char *prefix) { NEOERR *err = STATUS_OK; char *p, *l; int n = 0; char buf[256]; l = album; p = strchr(album, '/'); while (p != NULL) { *p = '\0'; snprintf(buf, sizeof(buf), "%s.%d", prefix, n); err = hdf_set_value(cgi->hdf, buf, l); if (err) break; snprintf(buf, sizeof(buf), "%s.%d.path", prefix, n++); err = hdf_set_value(cgi->hdf, buf, album); if (err) break; *p = '/'; l = p+1; p = strchr(l, '/'); } if (err) return nerr_pass(err); if (strlen(l)) { snprintf(buf, sizeof(buf), "%s.%d", prefix, n); err = hdf_set_value(cgi->hdf, buf, l); if (err) return nerr_pass(err); snprintf(buf, sizeof(buf), "%s.%d.path", prefix, n++); err = hdf_set_value(cgi->hdf, buf, album); if (err) return nerr_pass(err); } return STATUS_OK; } NEOERR *dowork_picture (CGI *cgi, char *album, char *picture) { NEOERR *err = STATUS_OK; char *base, *name; char path[_POSIX_PATH_MAX]; char buf[256]; int i, x, factor, y; int thumb_width, thumb_height; int pic_width, pic_height; ULIST *files = NULL; char t_album[_POSIX_PATH_MAX]; char t_pic[_POSIX_PATH_MAX]; char nfile[_POSIX_PATH_MAX]; char *ch; char *avi = NULL; int rotate; ch = strrchr(picture, '/'); if (ch != NULL) { *ch = '\0'; snprintf(t_album, sizeof(t_album), "%s/%s", album, picture); *ch = '/'; strncpy(t_pic, ch+1, sizeof(t_pic)); picture = t_pic; album = t_album; } base = hdf_get_value (cgi->hdf, "BASEDIR", NULL); if (base == NULL) { cgi_error (cgi, "No BASEDIR in imd file"); return nerr_raise(CGIFinished, "Finished"); } thumb_width = hdf_get_int_value (cgi->hdf, "ThumbWidth", 120); thumb_height = hdf_get_int_value (cgi->hdf, "ThumbWidth", 90); pic_width = hdf_get_int_value (cgi->hdf, "PictureWidth", 120); pic_height = hdf_get_int_value (cgi->hdf, "PictureWidth", 90); err = hdf_set_value (cgi->hdf, "Context", "picture"); if (err != STATUS_OK) return nerr_pass(err); snprintf (path, sizeof(path), "%s/%s", base, album); rotate = hdf_get_int_value(cgi->hdf, "Query.rotate", 0); if (rotate) { err = rotate_image(path, picture, rotate, nfile); if (err) return nerr_pass(err); picture = strrchr(nfile, '/') + 1; } err = hdf_set_value (cgi->hdf, "Album", album); if (err != STATUS_OK) return nerr_pass(err); err = hdf_set_value (cgi->hdf, "Album.Raw", album); if (err != STATUS_OK) return nerr_pass(err); err = export_album_path(cgi, album, "Album.Path"); if (err) return nerr_pass(err); err = hdf_set_value (cgi->hdf, "Picture", picture); if (err != STATUS_OK) return nerr_pass(err); err = load_images(path, &files, NULL, 0); if (err != STATUS_OK) return nerr_pass(err); err = uListSort(files, alpha_sort); if (err != STATUS_OK) return nerr_pass(err); i = -1; for (x = 0; x < uListLength(files); x++) { err = uListGet(files, x, (void *)&name); if (err) break; if (!strcmp(name, picture)) { i = x; break; } } if (i != -1) { for (x = 2; x > 0; x--) { if (i - x < 0) continue; err = uListGet(files, i-x, (void *)&name); if (err) break; snprintf(buf, sizeof(buf), "Show.%d", i-x); err = export_image(cgi, buf, path, name); if (err) break; } for (x = 0; x < 3; x++) { if (i + x > uListLength(files)) break; err = uListGet(files, i+x, (void *)&name); if (err) break; snprintf(buf, sizeof(buf), "Show.%d", i+x); err = export_image(cgi, buf, path, name); if (err) break; } snprintf (buf, sizeof(buf), "Show.%d.width", i); x = hdf_get_int_value (cgi->hdf, buf, -1); if (x != -1) { factor = 1; y = x; while (y > pic_width) { factor = factor * 2; /* factor++; */ y = x / factor; ne_warn("factor = %d, y = %d", factor, y); } snprintf (buf, sizeof(buf), "%d", y); hdf_set_value (cgi->hdf, "Picture.width", buf); snprintf (buf, sizeof(buf), "Show.%d.height", i); x = hdf_get_int_value (cgi->hdf, buf, -1); y = x / factor; snprintf (buf, sizeof(buf), "%d", y); hdf_set_value (cgi->hdf, "Picture.height", buf); } else { snprintf (buf, sizeof(buf), "%d", pic_width); hdf_set_value (cgi->hdf, "Picture.width", buf); snprintf (buf, sizeof(buf), "%d", pic_height); hdf_set_value (cgi->hdf, "Picture.height", buf); } snprintf (buf, sizeof(buf), "Show.%d.avi", i); avi = hdf_get_value (cgi->hdf, buf, NULL); if (avi) { err = hdf_set_value(cgi->hdf, "Picture.avi", avi); } err = scale_images (cgi, "Show", thumb_width, thumb_height, 0); } uListDestroy(&files, ULIST_FREE); return nerr_pass(err); } static int is_album(void *rock, char *filename) { char path[_POSIX_PATH_MAX]; char *prefix = (char *)rock; if (filename[0] == '.') return 0; snprintf(path, sizeof(path), "%s/%s", prefix, filename); if (isdir(path)) return 1; return 0; } NEOERR *dowork_album_overview (CGI *cgi, char *album) { NEOERR *err = STATUS_OK; DIR *dp; struct dirent *de; char path[_POSIX_PATH_MAX]; char buf[256]; int i = 0, x, y; int thumb_width, thumb_height; ULIST *files = NULL; ULIST *albums = NULL; char *name; thumb_width = hdf_get_int_value (cgi->hdf, "ThumbWidth", 120); thumb_height = hdf_get_int_value (cgi->hdf, "ThumbWidth", 90); err = ne_listdir_fmatch(album, &albums, is_album, album); if (err) return nerr_pass(err); err = uListSort(albums, alpha_sort); if (err) return nerr_pass(err); for (y = 0; y < uListLength(albums); y++) { err = uListGet(albums, y, (void *)&name); if (err) break; snprintf(path, sizeof(path), "%s/%s", album, name); snprintf(buf, sizeof(buf), "Albums.%d", i); err = hdf_set_value (cgi->hdf, buf, name); if (err != STATUS_OK) break; err = load_images(path, &files, NULL, 1); if (err != STATUS_OK) break; err = uListSort(files, alpha_sort); if (err != STATUS_OK) break; snprintf(buf, sizeof(buf), "Albums.%d.Count", i); err = hdf_set_int_value(cgi->hdf, buf, uListLength(files)); if (err != STATUS_OK) break; for (x = 0; (x < 4) && (x < uListLength(files)); x++) { err = uListGet(files, x, (void *)&name); if (err) break; snprintf(buf, sizeof(buf), "Albums.%d.Images.%d", i, x); err = export_image(cgi, buf, path, name); if (err) break; } uListDestroy(&files, ULIST_FREE); if (err != STATUS_OK) break; snprintf(buf, sizeof(buf), "Albums.%d.Images", i); err = scale_images (cgi, buf, thumb_width, thumb_height, 0); if (err != STATUS_OK) break; i++; } return nerr_pass(err); } NEOERR *dowork_album (CGI *cgi, char *album) { NEOERR *err; char *base; char buf[256]; char path[_POSIX_PATH_MAX]; int thumb_width, thumb_height; int per_page, start, next, prev, last; ULIST *files = NULL; char *name; int x; base = hdf_get_value (cgi->hdf, "BASEDIR", NULL); if (base == NULL) { cgi_error (cgi, "No BASEDIR in imd file"); return nerr_raise(CGIFinished, "Finished"); } thumb_width = hdf_get_int_value (cgi->hdf, "ThumbWidth", 120); thumb_height = hdf_get_int_value (cgi->hdf, "ThumbWidth", 90); per_page = hdf_get_int_value (cgi->hdf, "PerPage", 50); start = hdf_get_int_value (cgi->hdf, "Query.start", 0); err = hdf_set_value (cgi->hdf, "Album", album); if (err != STATUS_OK) return nerr_pass(err); err = hdf_set_value (cgi->hdf, "Album.Raw", album); if (err != STATUS_OK) return nerr_pass(err); err = export_album_path(cgi, album, "Album.Path"); if (err) return nerr_pass(err); err = hdf_set_value (cgi->hdf, "Context", "album"); if (err != STATUS_OK) return nerr_pass(err); snprintf (path, sizeof(path), "%s/%s", base, album); err = dowork_album_overview(cgi, path); if (err != STATUS_OK) return nerr_pass(err); err = load_images(path, &files, NULL, 0); if (err != STATUS_OK) return nerr_pass (err); err = uListSort(files, alpha_sort); if (err != STATUS_OK) return nerr_pass (err); err = hdf_set_int_value(cgi->hdf, "Album.Count", uListLength(files)); if (err != STATUS_OK) return nerr_pass (err); if (start > uListLength(files)) start = 0; next = start + per_page; if (next > uListLength(files)) next = uListLength(files); prev = start - per_page; if (prev < 0) prev = 0; last = uListLength(files) - per_page; if (last < 0) last = 0; err = hdf_set_int_value(cgi->hdf, "Album.Start", start); if (err != STATUS_OK) return nerr_pass (err); err = hdf_set_int_value(cgi->hdf, "Album.Next", next); if (err != STATUS_OK) return nerr_pass (err); err = hdf_set_int_value(cgi->hdf, "Album.Prev", prev); if (err != STATUS_OK) return nerr_pass (err); err = hdf_set_int_value(cgi->hdf, "Album.Last", last); if (err != STATUS_OK) return nerr_pass (err); for (x = start; x < next; x++) { err = uListGet(files, x, (void *)&name); if (err) break; snprintf(buf, sizeof(buf), "Images.%d", x); err = export_image(cgi, buf, path, name); if (err) break; } uListDestroy(&files, ULIST_FREE); if (err != STATUS_OK) return nerr_pass (err); err = scale_images (cgi, "Images", thumb_width, thumb_height, 0); if (err != STATUS_OK) return nerr_pass (err); return STATUS_OK; } NEOERR *dowork_image (CGI *cgi, char *image) { NEOERR *err = STATUS_OK; int maxW = 0, maxH = 0; char *basepath = ""; char *cache_basepath = "/tmp/.imgcache/"; char srcpath[_POSIX_PATH_MAX] = ""; char cachepath[_POSIX_PATH_MAX] = ""; char buf[256]; char *if_mod; int i, l, quality; struct stat s; struct tm *t; if ((i = hdf_get_int_value(cgi->hdf, "Query.width", 0)) != 0) { maxW = i; } if ((i = hdf_get_int_value(cgi->hdf, "Query.height", 0)) != 0) { maxH = i; } quality = hdf_get_int_value(cgi->hdf, "Query.quality", 0); if_mod = hdf_get_value(cgi->hdf, "HTTP.IfModifiedSince", NULL); basepath = hdf_get_value(cgi->hdf, "BASEDIR", NULL); if (basepath == NULL) { cgi_error (cgi, "No BASEDIR in imd file"); return nerr_raise(CGIFinished, "Finished"); } snprintf (srcpath, sizeof(srcpath), "%s/%s", basepath, image); snprintf (cachepath, sizeof(cachepath), "%s/%dx%d/%s", cache_basepath, maxW, maxH,image); if (stat(srcpath, &s)) { cgiwrap_writef("Status: 404\nContent-Type: text/html\n\n"); cgiwrap_writef("File %s not found.", srcpath); return nerr_raise_errno(NERR_IO, "Unable to stat file %s", srcpath); } t = gmtime(&(s.st_mtime)); if (if_mod && later_than(t, if_mod)) { cgiwrap_writef("Status: 304\nContent-Type: text/html\n\n"); cgiwrap_writef("Use Local Copy"); return STATUS_OK; } /* fprintf(stderr,"cachepath: %s\n",cachepath); */ ne_warn("srcpath: %s", srcpath); l = strlen(srcpath); if ((l>4 && !strcasecmp(srcpath+l-4, ".jpg")) || (l>4 && !strcasecmp(srcpath+l-4, ".thm")) || (l>5 && !strcasecmp(srcpath+l-5, ".jpeg"))) cgiwrap_writef("Content-Type: image/jpeg\n"); else if (l>4 && !strcasecmp(srcpath+l-4, ".gif")) cgiwrap_writef("Content-Type: image/gif\n"); else if (l>4 && !strcasecmp(srcpath+l-4, ".avi")) { ne_warn("found avi"); cgiwrap_writef("Content-Type: video/x-msvideo\n"); } t = gmtime(&(s.st_mtime)); strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", t); cgiwrap_writef("Last-modified: %s\n", buf); err = scale_and_display_image(srcpath,maxW,maxH,cachepath,quality); return nerr_pass(err); } int main(int argc, char **argv, char **envp) { NEOERR *err; CGI *cgi; char *image; char *album; char *imd_file; char *cs_file; char *picture; ne_warn("Starting IMD"); cgi_debug_init (argc,argv); cgiwrap_init_std (argc, argv, envp); nerr_init(); ne_warn("CGI init"); err = cgi_init(&cgi, NULL); if (err != STATUS_OK) { nerr_log_error(err); cgi_destroy(&cgi); return -1; } imd_file = hdf_get_value(cgi->hdf, "CGI.PathTranslated", NULL); ne_warn("Reading IMD file %s", imd_file); err = hdf_read_file (cgi->hdf, imd_file); if (err != STATUS_OK) { cgi_neo_error(cgi, err); nerr_log_error(err); cgi_destroy(&cgi); return -1; } cs_file = hdf_get_value(cgi->hdf, "Template", NULL); image = hdf_get_value(cgi->hdf, "Query.image", NULL); album = hdf_get_value(cgi->hdf, "Query.album", ""); picture = hdf_get_value(cgi->hdf, "Query.picture", NULL); if (image) { err = dowork_image(cgi, image); if (err) { nerr_log_error(err); cgi_destroy(&cgi); return -1; } } else { if (!picture) { err = dowork_album (cgi, album); } else { err = dowork_picture (cgi, album, picture); } if (err != STATUS_OK) { if (nerr_handle(&err, CGIFinished)) { /* pass */ } else { cgi_neo_error(cgi, err); nerr_log_error(err); cgi_destroy(&cgi); return -1; } } else { err = cgi_display(cgi, cs_file); if (err != STATUS_OK) { cgi_neo_error(cgi, err); nerr_log_error(err); cgi_destroy(&cgi); return -1; } } } cgi_destroy(&cgi); return 0; } clearsilver-0.10.5/imd/imd.cs0000644001211700116100000002165210261037511012677 00000000000000
src="1.gif">
width=8 src="3.gif"> height= src="?image=/&width=&height="> width=8 src="4.gif">
src="6.gif">
<?cs var:Title ?><?cs if:Context == "album" ?> <?cs var:Album.Raw ?> <?cs var:Album.Start + #1 ?> - <?cs var:Album.Next ?> of <?cs var:Album.Count ?><?cs else ?> <?cs var:Album.Raw ?> - <?cs var:Picture ?><?cs /if ?> / /

( images)
src="1.gif">
width=8 src="3.gif"> height= src="?image=//&width=&height="> width=8 src="4.gif">
src="6.gif">

#0 ?> First First   #0 ?> Prev Prev   - of   Next Next   Last Last
#PageWidth ?>
#0 ?> First First   #0 ?> Prev Prev   - of   Next Next   Last Last

src="1.gif">
width=18 src="3.gif"> height= src="?image=/" AUTOSTART=true> height= src="?image=/&width=&height=&quality=1" dynsrc="?image=/&width=&height=&quality=1"> width=18 src="4.gif">
src="6.gif">
Raw Video Raw Picture
  Rotate: Left - Right - Flip clearsilver-0.10.5/imd/imdm.py0000755001211700116100000001417410261037512013104 00000000000000#!/usr/local/bin/python # # imdm # # IMage Display Master # # This uses the affiliated C-cgi "imd" to build a caching image display # server with only passive Apache cgis. # import sys,os,string import cgi # this function should find the first four images inside a # nested subdirectory albumstartfile = "/~jeske/Images/jeskealbum.imd" imagestartfile = "/~jeske/Images/jeskealbum.imc" THUMB_WIDTH = 120 THUMB_HEIGHT = 90 # ------------------------------------------------------------------------------------ # # utility functions def albumoverview(basedir,sub_dir,count = 4,skip = 0): images = [] fulldir = os.path.join(basedir,sub_dir) for a_entry in os.listdir(fulldir): fullpath = os.path.join(fulldir,a_entry) if os.path.isfile(fullpath): if string.lower(string.split(a_entry,".")[-1]) in ["jpeg","jpg"]: images.append(os.path.join(sub_dir,a_entry)) elif os.path.isdir(fullpath): images + albumoverview(basedir,os.path.join(sub_dir,a_entry),1) if len(images) >= (count + skip): return images[skip:] return images[skip:] def makethumbnailimgtag(filename,width=THUMB_WIDTH,height=THUMB_HEIGHT): global imagestartfile return '' % (imagestartfile,filename,width,height) def makealbumurl(dir): global albumstartfile return "%s?album=%s" % (albumstartfile,dir) def makepictureurl(dir,picture): global albumstartfile return "%s?album=%s&picture=%s" % (albumstartfile,dir,picture) # ------------------------------------------------------------------------------------ # # picturedisplay def picturedisplay(basedir,album,picture): sys.stdout.write("top " % albumstartfile) sys.stdout.write("-- %s" % (makealbumurl(album),album)) imagename = os.path.join(album,picture) sys.stdout.write("

") sys.stdout.write("
\n") sys.stdout.write(makethumbnailimgtag(imagename,width=600,height=500)) sys.stdout.write("
\n") images = albumoverview(basedir,album,count=500) image_index = None for x in range(len(images)): if images[x] == imagename: image_index = x break if not image_index is None: sys.stdout.write("
") # pre-images for i in range(1,3): pic_index = image_index - i picture_path = string.join(string.split(images[pic_index],'/')[1:],'/') sys.stdout.write("" % (makepictureurl(album,picture_path),makethumbnailimgtag(images[pic_index]))) sys.stdout.write("
") # post-images for i in range(1,3): pic_index = image_index + i if pic_index >= len(images): pic_index = pic_index - len(images) picture_path = string.join(string.split(images[pic_index],'/')[1:],'/') sys.stdout.write("" % (makepictureurl(album,picture_path), makethumbnailimgtag(images[pic_index]))) sys.stdout.write("
%s%s
\n") # navigation # ------------------------------------------------------------------------------------ # # albumdisplay def albumdisplay(basedir,album,columns=7,rows=5): next_page = 0 sys.stdout.write("
%s
" % album) imgcount = columns * rows images = albumoverview(basedir,album,count=(imgcount + 1),skip=0) if len(images) > imgcount: images = images[:-1] next_page = 1 while images: sys.stdout.write("
") for a_col in range(columns): if len(images): picture_path = string.join(string.split(images[0],'/')[1:],'/') sys.stdout.write("" % (makepictureurl(album,picture_path),makethumbnailimgtag(images[0]))) images = images[1:] sys.stdout.write("
%s
") if next_page: sys.stdout.write("more...") # ------------------------------------------------------------------------------------ # # topalbumoverview def topalbumoverview(dir): for a_dir in os.listdir(dir): if os.path.isdir(os.path.join(dir,a_dir)): sys.stdout.write("
") sys.stdout.write("") sys.stdout.write("" % (makealbumurl(a_dir),a_dir)) sys.stdout.write("
%s
") for a_file in albumoverview(dir,a_dir): picture_path = string.join(string.split(a_file,'/')[1:],'/') sys.stdout.write("\n" % (makepictureurl(a_dir,picture_path),makethumbnailimgtag(a_file))) sys.stdout.write("
%s
\n

\n") # ------------------------------------------------------------------------------------ # # readvars() -- simple file format reader def readvars(filename): vars = {} data = open(filename,"rb").read() lines = string.split(data,"\n") for a_line in lines: stripped_line = string.strip(a_line) if not stripped_line or stripped_line[0] == "#": continue try: key,value = string.split(a_line,"=") vars[key] = value except: pass return vars # ------------------------------------------------------------------------------------ # # main() def main(): global cgiform cgiform = cgi.FieldStorage() sys.stdout.write("Content-Type: text/html\n\n") sys.stdout.write("

HTML Image Viewer!

") myvars = readvars(os.environ['PATH_TRANSLATED']) sys.stderr.write(repr(myvars)) global albumstartfile, imagestartfile albumstartfile = os.environ['PATH_INFO'] imagestartfile = myvars['IMGSTARTFILE'] BASEDIR = myvars['BASEDIR'] album = cgiform.getvalue('album',None) picture = cgiform.getvalue('picture',None) if album is None: topalbumoverview(BASEDIR) elif picture is None: albumdisplay(BASEDIR,album) else: picturedisplay(BASEDIR,album,picture) if __name__ == "__main__": main() clearsilver-0.10.5/imd/test.in0000644001211700116100000000010610261037512013076 00000000000000PATH_TRANSLATED=/home/blong/public_html/Images/test.imd QUERY_STRING= clearsilver-0.10.5/java-jni/0000755001211700116100000000000010645505045012607 500000000000000clearsilver-0.10.5/java-jni/CGI.java0000644001211700116100000000040510560507211013764 00000000000000 import java.io.*; import java.util.*; class CGI { public int _cgiptr; static { JNI.loadLibrary(); } public CGI() { _cgiptr = _init(); } private static native int _init(); private static native void parse(); }; clearsilver-0.10.5/java-jni/CS.java0000644001211700116100000000532110560507211013671 00000000000000package org.clearsilver; import java.io.*; import java.util.*; public class CS { public int csptr; protected HDF globalHDF; protected HDF localHDF; static { JNI.loadLibrary(); } public CS(HDF ho) { this.globalHDF = null; this.localHDF = ho; csptr = _init(ho.hdfptr); } // Construct with global HDF to search if local HDF returns null public CS(HDF ho, HDF global) { this(ho); this.globalHDF = global; if (global != null) { _setGlobalHdf(csptr,global.hdfptr); } } // Specify a new/different global HDF public void setGlobalHDF(HDF global) { _setGlobalHdf(csptr,global.hdfptr); this.globalHDF = global; } // Return global hdf in use public HDF getGlobalHDF() { return this.globalHDF; } public void close() { if (csptr != 0) { _dealloc(csptr); csptr = 0; } } public void finalize() { close(); } public void parseFile(String filename) { if (csptr == 0) { throw new NullPointerException("CS is closed."); } _parseFile(csptr, filename, fileLoader != null); } public void parseStr(String content) { if (csptr == 0) { throw new NullPointerException("CS is closed."); } _parseStr(csptr,content); } public String render() { if (csptr == 0) { throw new NullPointerException("CS is closed."); } return _render(csptr); } protected String fileLoad(String filename) throws IOException, FileNotFoundException { if (csptr == 0) { throw new NullPointerException("CS is closed."); } CSFileLoader aFileLoader = fileLoader; if (aFileLoader == null) { throw new NullPointerException("No fileLoader specified."); } else { String result = aFileLoader.load(localHDF, filename); if (result == null) { throw new NullPointerException("CSFileLoader.load() returned null"); } return result; } } // The optional CS file loader to use to read in files private CSFileLoader fileLoader = null; /** * Get the file loader in use, if any. * @return the file loader in use. */ public CSFileLoader getFileLoader() { return fileLoader; } /** * Set the CS file loader to use * @param fileLoader the file loader that should be used. */ public void setFileLoader(CSFileLoader fileLoader) { this.fileLoader = fileLoader; } private native int _init(int ptr); private native void _dealloc(int ptr); private native void _parseFile(int ptr, String filename, boolean use_cb); private native void _parseStr(int ptr, String content); private native String _render(int ptr); private native void _setGlobalHdf(int csptr, int hdfptr); }; clearsilver-0.10.5/java-jni/CSFileLoader.java0000644001211700116100000000107510547547674015650 00000000000000package org.clearsilver; import java.io.IOException; /** * Interface for CS file hook * * @author smarti@google.com (Sergio Marti) */ public interface CSFileLoader { /** * Callback method that is expected to return the contents of the specified * file as a string. * @param hdf the HDF structure associated with HDF or CS object making the * callback. * @param filename the name of the file that should be loaded. * @return a string containing the contents of the file. */ public String load(HDF hdf, String filename) throws IOException; } clearsilver-0.10.5/java-jni/CSTest.java0000644001211700116100000002360510547547674014564 00000000000000 import java.io.*; import java.util.*; import org.clearsilver.CS; import org.clearsilver.CSFileLoader; import org.clearsilver.HDF; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class CSTest { public static void main( String [] args ) throws IOException { org.clearsilver.HDF hdf = new HDF(); System.out.println("Testing HDF set and dump\n"); hdf.setValue("Foo.Bar","10"); hdf.setValue("Foo.Baz","20"); System.out.println( hdf.dump() ); System.out.println("Testing HDF get\n"); String foo = hdf.getValue("Foo.Bar", "30"); System.out.println( foo ); foo = hdf.getValue("Foo.Baz", "30"); System.out.println( foo ); System.out.println( "----" ); System.out.println("Testing HDF setSymLink\n"); hdf.setSymLink("Foo.Baz2","Foo.Baz"); foo = hdf.getValue("Foo.Baz", "30"); System.out.println( foo ); System.out.println( "----" ); System.out.println("Testing HDF get where default value is null\n"); foo = hdf.getValue("Foo.Bar", null); System.out.println("foo = " + foo); foo = hdf.getValue("Foo.Nonexistent", null); System.out.println("foo = " + foo); System.out.println( "----" ); int fooInt = hdf.getIntValue("Foo.Bar", 30); System.out.println("Testing HDF get int\n"); System.out.println( fooInt ); System.out.println( "----" ); org.clearsilver.CS cs = new CS(hdf); System.out.println("Testing HDF parse/render\n"); String tmplstr = "Foo.Bar:\nFoo.Baz:\n"; System.out.println(tmplstr); System.out.println("----"); cs.parseStr(tmplstr); System.out.println(cs.render()); // test registered functions System.out.println("Testing registered string functions\n"); hdf.setValue("Foo.EscapeTest","abc& 231<>/?"); tmplstr = " "; cs.parseStr(tmplstr); System.out.println(cs.render()); cs = new CS(hdf); System.out.println("Testing white space stripping\n"); // test white space stripping tmplstr = " This is a string without whitespace stripped"; cs.parseStr(tmplstr); System.out.println(cs.render()); hdf.setValue("ClearSilver.WhiteSpaceStrip", "1"); System.out.println(cs.render()); // Now, test debug dump System.out.println("Testing debug dump\n"); hdf.setValue("ClearSilver.DisplayDebug", "1"); System.out.println(cs.render()); System.out.println("Final HDF dump\n"); System.out.println( hdf.dump() ); // Now, test reading an HDF file from disk System.out.println("Testing HDF.readFile()\n"); HDF file_hdf = new HDF(); file_hdf.readFile("testdata/test1.hdf"); System.out.println(file_hdf.dump()); System.out.println("Testing HDF.readFile() for a file that doesn't exist"); try { file_hdf.readFile("testdata/doesnt_exist.hdf"); } catch (Exception e) { // The error message contains line numbers for functions in // neo_hdf.c, and I don't want this test to fail if the line numbers // change, so I'm not going to print out the exception message here. // The important thing to test here is that an exception is thrown // System.out.println(e + "\n"); System.out.println("Caught exception of type " + e.getClass().getName() + "\n"); } System.out.println("Testing HDF.writeFile()\n"); file_hdf.writeFile("test1_out.hdf"); file_hdf.writeFileAtomic("test1_out2.hdf"); System.out.println("Testing HDF.writeString()\n"); System.out.println(file_hdf.writeString()); System.out.println("Testing HDF.getObj()"); HDF foo_hdf = file_hdf.getObj("Foo"); System.out.println(foo_hdf.dump()); System.out.println("Testing HDF.objName()"); System.out.println("Should be \"Foo\": " + foo_hdf.objName()); System.out.println("Should be \"Bar\": " + foo_hdf.getObj("Bar").objName()); System.out.println("Should be null: " + file_hdf.objName() + "\n"); System.out.println("Testing HDF.objValue()"); System.out.println("Value of Foo.Bar: " + foo_hdf.getObj("Bar").objValue()); System.out.println("Value of root node: " + file_hdf.objValue() + "\n"); System.out.println("Testing HDF.objChild()"); HDF child_hdf = foo_hdf.objChild(); System.out.println("First child name: " + child_hdf.objName() + "\n"); System.out.println("Testing HDF.objNext()"); HDF next_hdf = child_hdf.objNext(); System.out.println("Next child name: " + next_hdf.objName()); next_hdf = next_hdf.objNext(); System.out.println("Next child (should be null): " + next_hdf + "\n"); System.out.println("Testing HDF.copy()"); HDF one = new HDF(); one.setValue("name", "barneyb"); one.setValue("age", "25"); HDF two = new HDF(); two.setValue("entity.type", "person"); two.copy("entity.value", one); System.out.println("name should be barneyb: " + two.getValue("entity.value.name", "--undefined--") +"\n"); System.out.println("Testing HDF.exportDate()"); HDF date_hdf = new HDF(); date_hdf.exportDate("DatePST", "US/Pacific", 1142308218); date_hdf.exportDate("DateEST", "US/Eastern", 1142308218); System.out.println(date_hdf.dump()); // Test default escaping mode: html HDF escape_hdf = new HDF(); System.out.println("Testing escape mode: html"); System.out.println("Config.VarEscapeMode = \"html\""); escape_hdf.setValue("Config.VarEscapeMode", "html"); cs = new CS(escape_hdf); System.out.println("Some.HTML = " + ""); escape_hdf.setValue("Some.HTML", ""); tmplstr = "Default HTML escaping: \n"; System.out.println(tmplstr); System.out.println("----"); cs.parseStr(tmplstr); System.out.println(cs.render()); // Test default escaping mode: js escape_hdf = new HDF(); System.out.println("Testing escape mode: js"); System.out.println("Config.VarEscapeMode = \"js\""); escape_hdf.setValue("Config.VarEscapeMode", "js"); cs = new CS(escape_hdf); System.out.println("Some.HTML = " + ""); escape_hdf.setValue("Some.HTML", ""); tmplstr = "Default JS escaping: \n"; System.out.println(tmplstr); System.out.println("----"); cs.parseStr(tmplstr); System.out.println(cs.render()); // Test default escaping mode: url escape_hdf = new HDF(); System.out.println("Testing escape mode: url"); System.out.println("Config.VarEscapeMode = \"url\""); escape_hdf.setValue("Config.VarEscapeMode", "url"); cs = new CS(escape_hdf); System.out.println("Some.HTML = " + ""); escape_hdf.setValue("Some.HTML", ""); tmplstr = "Default URL escaping: \n"; System.out.println(tmplstr); System.out.println("----"); cs.parseStr(tmplstr); System.out.println(cs.render()); // Test escape blocks escape_hdf = new HDF(); System.out.println("Testing escape blocks: none"); System.out.println("Config.VarEscapeMode = \"none\""); escape_hdf.setValue("Config.VarEscapeMode", "none"); cs = new CS(escape_hdf); System.out.println("Some.HTML = " + ""); escape_hdf.setValue("Some.HTML", ""); tmplstr = "url escape block: \n" + "" + " " + "\n" + "js escape block: \n" + "" + " " + "\n" + "html escape block: \n" + "" + " " + "\n"; System.out.println(tmplstr); System.out.println("----"); cs.parseStr(tmplstr); System.out.println(cs.render()); System.out.println("Testing HDF.readFile() with callback\n"); file_hdf = new HDF(); file_hdf.setFileLoader(new CSTestLoader()); file_hdf.readFile("testdata/test1.hdf"); System.out.println(file_hdf.dump()); System.out.println("Testing CS.parseFile() with callback\n"); cs = new CS(file_hdf); cs.setFileLoader(new CSTestLoader()); cs.parseFile("testdata/test.cs"); System.out.println(cs.render()); } }; class CSTestLoader implements CSFileLoader { public String load(HDF hdf, String filename) throws IOException { System.out.println("CSTestLoader::Load " + filename + "\n"); String data = readFile(new File(filename)); System.out.println("---- file begin ----\n" + data + "\n---- file end ----\n"); return data; } private String readFile(File file) throws IOException { InputStreamReader fin = new InputStreamReader(new FileInputStream(file), "UTF-8"); StringBuilder sb = new StringBuilder(1024); char[] charbuf = new char[1024]; int len = 0; while ((len = fin.read(charbuf)) != -1) { sb.append(charbuf, 0, len); } return sb.toString(); } }; clearsilver-0.10.5/java-jni/CSUtil.java0000644001211700116100000000344510541664744014552 00000000000000package org.clearsilver; import java.util.LinkedList; import java.util.List; import java.io.File; /** * Utility class containing helper methods * * @author smarti@google.com (Sergio Marti) */ public class CSUtil { private CSUtil() { } public static final String HDF_LOADPATHS = "hdf.loadpaths"; /** * Helper function that returns a concatenation of the loadpaths in the * provided HDF. * @param hdf an HDF structure containing load paths. * @return A list of loadpaths in order in which to search. * @throws NullPointerException if no loadpaths are found. */ public static List getLoadPaths(HDF hdf) { List list = new LinkedList(); HDF loadpathsHdf = hdf.getObj(HDF_LOADPATHS); if (loadpathsHdf == null) { throw new NullPointerException("No HDF loadpaths located in the specified" + " HDF structure"); } for (HDF lpHdf = loadpathsHdf.objChild(); lpHdf != null; lpHdf = lpHdf.objNext()) { list.add(lpHdf.objValue()); } return list; } /** * Given an ordered list of directories to look in, locate the specified file. * Returns null if file not found. * @param loadpaths the ordered list of paths to search. * @param filename the name of the file. * @return a File object corresponding to the file. null if * file not found. */ public static File locateFile(List loadpaths, String filename) { if (filename == null) { throw new NullPointerException("No filename provided"); } if (loadpaths == null) { throw new NullPointerException("No loadpaths provided."); } for (String path : loadpaths) { File file = new File(path, filename); if (file.exists()) { return file; } } return null; } } clearsilver-0.10.5/java-jni/HDF.java0000644001211700116100000003117410560507211013772 00000000000000package org.clearsilver; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; /** This class is a wrapper around the HDF C API. Many features of the C API * are not yet exposed through this wrapper. */ public class HDF { int hdfptr; // stores the C HDF* pointer HDF root; // If this is a child HDF node, points at the root node of // the tree. For root nodes this is null. A child node needs // to hold a reference on the root to prevent the root from // being GC-ed. static { JNI.loadLibrary(); } /** Constructs an empty HDF dataset */ public HDF() { hdfptr = _init(); root = null; } /** Constructs an HDF child node. Used by other methods in this class when * a child node needs to be constructed. */ private HDF(int hdfptr, HDF parent) { this.hdfptr = hdfptr; this.root = (parent.root != null) ? parent.root : parent; } /** Clean up allocated memory if neccesary. close() allows application * to force clean up. */ public void close() { // Only root nodes have ownership of the C HDF pointer, so only a root // node needs to dealloc hdfptr.dir if ( root == null) { if (hdfptr != 0) { _dealloc(hdfptr); hdfptr = 0; } } } /** Call close() just in case when deallocating Java object. */ // Should be protected access (like Object). protected void finalize() throws Throwable { close(); super.finalize(); } /** Loads the contents of the specified HDF file from disk into the current * HDF object. The loaded contents are merged with the existing contents. */ public boolean readFile(String filename) throws IOException, FileNotFoundException { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _readFile(hdfptr, filename, fileLoader != null); } protected String fileLoad(String filename) throws IOException, FileNotFoundException { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } CSFileLoader aFileLoader = fileLoader; if (aFileLoader == null) { throw new NullPointerException("No fileLoader specified."); } else { String result = aFileLoader.load(this, filename); if (result == null) { throw new NullPointerException("CSFileLoader.load() returned null"); } return result; } } // The optional CS file loader to use to read in files private CSFileLoader fileLoader = null; /** * Get the file loader in use, if any. * @return the file loader in use. */ public CSFileLoader getFileLoader() { return fileLoader; } /** * Set the CS file loader to use * @param fileLoader the file loader that should be used. */ public void setFileLoader(CSFileLoader fileLoader) { this.fileLoader = fileLoader; } /** Serializes HDF contents to a file (readable by readFile) */ public boolean writeFile(String filename) throws IOException { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _writeFile(hdfptr, filename); } /** Serializes HDF contents to a file (readable by readFile), but * writes the file atomically by writing to a temp file then doing a * rename(2) on it. */ public boolean writeFileAtomic(String filename) throws IOException { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _writeFileAtomic(hdfptr, filename); } /** Parses/loads the contents of the given string as HDF into the current * HDF object. The loaded contents are merged with the existing contents. */ public boolean readString(String data) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _readString(hdfptr, data); } /** Serializes HDF contents to a string (readable by readString) */ public String writeString() { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _writeString(hdfptr); } /** Retrieves the integer value at the specified path in this HDF node's * subtree. If the value does not exist, or cannot be converted to an * integer, default_value will be returned. */ public int getIntValue(String hdfname, int default_value) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _getIntValue(hdfptr,hdfname,default_value); } /** Retrieves the value at the specified path in this HDF node's subtree. */ public String getValue(String hdfname, String default_value) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _getValue(hdfptr,hdfname,default_value); } /** Sets the value at the specified path in this HDF node's subtree. */ public void setValue(String hdfname, String value) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } _setValue(hdfptr,hdfname,value); } /** Remove the specified subtree. */ public void removeTree(String hdfname) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } _removeTree(hdfptr,hdfname); } /** Links the src hdf name to the dest. */ public void setSymLink(String hdf_name_src, String hdf_name_dest) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } _setSymLink(hdfptr,hdf_name_src,hdf_name_dest); } /** Export a date to a clearsilver tree using a specified timezone */ public void exportDate(String hdfname, TimeZone timeZone, Date date) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } Calendar cal = Calendar.getInstance(timeZone); cal.setTime(date); String sec = Integer.toString(cal.get(Calendar.SECOND)); setValue(hdfname + ".sec", sec.length() == 1 ? "0" + sec : sec); String min = Integer.toString(cal.get(Calendar.MINUTE)); setValue(hdfname + ".min", min.length() == 1 ? "0" + min : min); setValue(hdfname + ".24hour", Integer.toString(cal.get(Calendar.HOUR_OF_DAY))); // java.util.Calendar uses represents 12 o'clock as 0 setValue(hdfname + ".hour", Integer.toString( cal.get(Calendar.HOUR) == 0 ? 12 : cal.get(Calendar.HOUR))); setValue(hdfname + ".am", cal.get(Calendar.AM_PM) == Calendar.AM ? "1" : "0"); setValue(hdfname + ".mday", Integer.toString(cal.get(Calendar.DAY_OF_MONTH))); setValue(hdfname + ".mon", Integer.toString(cal.get(Calendar.MONTH)+1)); setValue(hdfname + ".year", Integer.toString(cal.get(Calendar.YEAR))); setValue(hdfname + ".2yr", Integer.toString(cal.get(Calendar.YEAR)).substring(2)); setValue(hdfname + ".wday", Integer.toString(cal.get(Calendar.DAY_OF_WEEK))); boolean tzNegative = timeZone.getRawOffset() < 0; int tzAbsolute = java.lang.Math.abs(timeZone.getRawOffset()/1000); String tzHour = Integer.toString(tzAbsolute/3600); String tzMin = Integer.toString(tzAbsolute/60 - (tzAbsolute/3600)*60); String tzString = (tzNegative ? "-" : "+") + (tzHour.length() == 1 ? "0" + tzHour : tzHour) + (tzMin.length() == 1 ? "0" + tzMin : tzMin); setValue(hdfname + ".tzoffset", tzString); } /** Export a date to a clearsilver tree using a specified timezone */ public void exportDate(String hdfname, String tz, int tt) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } TimeZone timeZone = TimeZone.getTimeZone(tz); if (timeZone == null) { throw new RuntimeException("Unknown timezone: " + tz); } Date date = new Date((long)tt * 1000); exportDate(hdfname, timeZone, date); } /** Retrieves the HDF object that is the root of the subtree at hdfpath, or * null if no object exists at that path. */ public HDF getObj(String hdfpath) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } int obj_ptr = _getObj(hdfptr, hdfpath); if ( obj_ptr == 0 ) { return null; } return new HDF(obj_ptr, this); } /** Retrieves the HDF for the first child of the root of the subtree * at hdfpath, or null if no child exists of that path or if the * path doesn't exist. */ public HDF getChild(String hdfpath) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } int obj_ptr = _getChild(hdfptr, hdfpath); if ( obj_ptr == 0 ) { return null; } return new HDF(obj_ptr, this); } /** Return the root of the tree where the current node lies. If the * current node is the root, return this. */ public HDF getRootObj() { return root != null ? root : this; } /** Retrieves the HDF object that is the root of the subtree at * hdfpath, create the subtree if it doesn't exist */ public HDF getOrCreateObj(String hdfpath) { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } int obj_ptr = _getObj(hdfptr, hdfpath); if ( obj_ptr == 0 ) { // Create a node _setValue(hdfptr, hdfpath, ""); obj_ptr = _getObj( hdfptr, hdfpath ); if ( obj_ptr == 0 ) { return null; } } return new HDF(obj_ptr, this); } /** Returns the name of this HDF node. The root node has no name, so * calling this on the root node will return null. */ public String objName() { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _objName(hdfptr); } /** Returns the value of this HDF node, or null if this node has no value. * Every node in the tree can have a value, a child, and a next peer. */ public String objValue() { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _objValue(hdfptr); } /** Returns the child of this HDF node, or null if there is no child. * Use this in conjunction with objNext to walk the HDF tree. Every node * in the tree can have a value, a child, and a next peer. */ public HDF objChild() { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } int child_ptr = _objChild(hdfptr); if ( child_ptr == 0 ) { return null; } return new HDF(child_ptr, this); } /** Returns the next sibling of this HDF node, or null if there is no next * sibling. Use this in conjunction with objChild to walk the HDF tree. * Every node in the tree can have a value, a child, and a next peer. */ public HDF objNext() { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } int next_ptr = _objNext(hdfptr); if ( next_ptr == 0 ) { return null; } return new HDF(next_ptr, this); } public void copy(String hdfpath, HDF src) { if (hdfptr == 0 || src.hdfptr == 0) { throw new NullPointerException("HDF is closed."); } _copy(hdfptr, hdfpath, src.hdfptr); } /** * Generates a string representing the content of the HDF tree rooted at * this node. */ public String dump() { if (hdfptr == 0) { throw new NullPointerException("HDF is closed."); } return _dump(hdfptr); } private static native int _init(); private static native void _dealloc(int ptr); private native boolean _readFile(int ptr, String filename, boolean use_cb); private static native boolean _writeFile(int ptr, String filename); private static native boolean _writeFileAtomic(int ptr, String filename); private static native boolean _readString(int ptr, String data); private static native String _writeString(int ptr); private static native int _getIntValue(int ptr, String hdfname, int default_value); private static native String _getValue(int ptr, String hdfname, String default_value); private static native void _setValue(int ptr, String hdfname, String hdf_value); private static native void _removeTree(int ptr, String hdfname); private static native void _setSymLink(int ptr, String hdf_name_src, String hdf_name_dest); private static native int _getObj(int ptr, String hdfpath); private static native int _getChild(int ptr, String hdfpath); private static native int _objChild(int ptr); private static native int _objNext(int ptr); private static native String _objName(int ptr); private static native String _objValue(int ptr); private static native void _copy(int destptr, String hdfpath, int srcptr); private static native String _dump(int ptr); } clearsilver-0.10.5/java-jni/JNI.java0000644001211700116100000000413510560507211014006 00000000000000package org.clearsilver; /** * Loads the ClearSilver JNI library. * *

By default, it attempts to load the library 'clearsilver-jni' from the * path specified in the 'java.library.path' system property.

* *

If this fails, the JVM exits with a code of 1. However, this strategy * can be changed using {@link #setFailureCallback(Runnable)}.

*/ public class JNI { /** * Failure callback strategy that writes a message to sysout, then calls * System.exit(1). */ public static Runnable EXIT_JVM = new Runnable() { public void run() { System.out.println("Could not load '" + libraryName + "'"); System.out.println("java.library.path = " + System.getProperty("java.library.path")); System.exit(1); } }; /** * Failure callback strategy that throws an UnsatisfiedLinkError, which * should be caught be client code. */ public static Runnable THROW_ERROR = new Runnable() { public void run() { throw new UnsatisfiedLinkError("Could not load '" + libraryName + "'"); } }; private static Runnable failureCallback = EXIT_JVM; private static Object callbackLock = new Object(); private static String libraryName = "clearsilver-jni"; /** * Attempts to load the ClearSilver JNI library. * * @see #setFailureCallback(Runnable) */ public static void loadLibrary() { try { System.loadLibrary(libraryName); } catch (UnsatisfiedLinkError e) { synchronized (callbackLock) { if (failureCallback != null) { failureCallback.run(); } } } } /** * Sets a callback for what should happen if the JNI library cannot * be loaded. The default is {@link #EXIT_JVM}. * * @see #EXIT_JVM * @see #THROW_ERROR */ public static void setFailureCallback(Runnable failureCallback) { synchronized(callbackLock) { JNI.failureCallback = failureCallback; } } /** * Set name of JNI library to load. Default is 'clearsilver-jni'. */ public static void setLibraryName(String libraryName) { JNI.libraryName = libraryName; } }clearsilver-0.10.5/java-jni/Makefile0000644001211700116100000000471110560507211014163 00000000000000 .SUFFIXES: .java .class ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk NEO_UTIL_SO = libclearsilver-jni.so ifeq ($(OSTYPE),Darwin) NEO_UTIL_SO = libclearsilver-jni.jnilib endif NEO_UTIL_JAVA_SRC = HDF.java CS.java CSUtil.java CSFileLoader.java JNI.java # CGI.java NEO_UTIL_JAVA_JAR = clearsilver.jar NEO_UTIL_SRC = j_neo_util.c j_neo_cs.c NEO_UTIL_OBJ = $(NEO_UTIL_SRC:%.c=%.o) CFLAGS += $(JAVA_INCLUDE_PATH) DLIBS += -lneo_cgi -lneo_cs -lneo_utl LIBS += $(DLIBS) ifneq ($(OSTYPE),Darwin) LDFLAGS += -Wl,-soname=$(NEO_UTIL_SO) endif TARGETS = org_clearsilver_HDF.h org_clearsilver_CS.h $(NEO_UTIL_SO) all: $(TARGETS) test $(NEO_UTIL_JAVA_JAR): $(NEO_UTIL_JAVA_SRC) $(MKDIR) org/clearsilver $(JAVAC) -d . $(NEO_UTIL_JAVA_SRC) $(JAR) cf $(NEO_UTIL_JAVA_JAR) org $(RM) -r org org_clearsilver_HDF.h: $(NEO_UTIL_JAVA_JAR) $(JAVAH) -classpath $(NEO_UTIL_JAVA_JAR) -jni org.clearsilver.HDF org_clearsilver_CS.h: $(NEO_UTIL_JAVA_JAR) $(JAVAH) -classpath $(NEO_UTIL_JAVA_JAR) -jni org.clearsilver.CS CSTest.class: CSTest.java $(JAVAC) -classpath $(NEO_UTIL_JAVA_JAR) CSTest.java gold: CSTest.class @/bin/sh -c "LD_LIBRARY_PATH=$(NEOTONIC_ROOT)/java-jni; export LD_LIBRARY_PATH; CLASSPATH=$(NEO_UTIL_JAVA_JAR):.; export CLASSPATH; $(JAVA_PATH)/bin/java CSTest" > javatest.gold @echo "Generated gold files" test: CSTest.class @echo "Running java test" @failed=0; \ rm -f javatest.out; \ LD_LIBRARY_PATH=$(NEOTONIC_ROOT)/java-jni; export LD_LIBRARY_PATH; \ CLASSPATH=$(NEO_UTIL_JAVA_JAR):.; export CLASSPATH; \ $(JAVA_PATH)/bin/java CSTest > javatest.out; \ diff javatest.out javatest.gold > /dev/null 2>&1; \ return_code=$$?; \ if [ $$return_code -ne 0 ]; then \ diff javatest.out javatest.gold > javatest.err; \ echo "Failed Java Test: CSTest"; \ echo " See javatest.out and javatest.err"; \ failed=1; \ fi; \ if [ $$failed -eq 1 ]; then \ exit 1; \ fi; @echo "Passed java test" CGI.h: CGI.class $(JAVAH) -jni CGI $(NEO_UTIL_SO): $(NEO_UTIL_JAVA_JAR) $(NEO_UTIL_OBJ) $(DEP_LIBS) $(LDSHARED) -o $@ $(LDFLAGS) $(NEO_UTIL_OBJ) $(LIBS) # I guess we'll just stick the .jar file in the lib directory install: all $(INSTALL) $(NEO_UTIL_SO) $(DESTDIR)$(libdir) $(INSTALL) $(NEO_UTIL_JAVA_JAR) $(DESTDIR)$(libdir) clean: $(RM) *.o *.so $(RM) -r org $(RM) org_clearsilver_*.h $(RM) *.class $(RM) org_clearsilver_HDF.h org_clearsilver_CS.h $(RM) Makefile.depends distclean: clean $(RM) -f Makefile.depends $(TARGETS) clearsilver-0.10.5/java-jni/README-bin.txt0000644001211700116100000000157110261037512014770 00000000000000--------------------------------- Clearsilver JavaJNI wrapper by David Jeske Distributed under the Neotonic ClearSilver License ---------------------------------- This is a binary compile of a Java JNI wrapper for the ClearSilver templating library. This version is compiled on: x86 Linux (Linux 2.2.x - RedHat 6.2) INSTALLING You must put the native library (libclearsilver-jni.so) into a standard library location (i.e. like /lib), or make sure that Java can find it by using the java command line directive: -Djava.library.path=/somewhere/else Then you must put the clearsilver.jar file into your java CLASSPATH. USING See the example CSTest.java for an example of how to import and use the clearsilver objects. USING in a servlet Since the most common usage of Clearsilver is in a servlet, we've provided some examples of how to use it in the servlet/ directory. - clearsilver-0.10.5/java-jni/README.txt0000644001211700116100000000207410261037512014221 00000000000000---------------------------------- Clearsilver JavaJNI wrapper by David Jeske Distributed under the Neotonic ClearSilver License ---------------------------------- This is a Java Native Interface (JNI) wrapper for the ClearSilver templating library. The files in this directory build into both a clearsilver.jar file with Java classes, and a native library libclearsilver-jni.so. BUILDING After building clearsilver, just type "make" twice. The first time you build it builds the depend, and throw some random error, I don't know why. INSTALLING You must put the native library into a standard library location (i.e. like /lib), or make sure that Java can find it by using the java command line directive: -Djava.library.path=/somewhere/else Then you must put the clearsilver.jar file into your java CLASSPATH. USING See the example CSTest.java for an example of how to import and use the clearsilver objects. USING in a servlet Since the most common usage of Clearsilver is in a servlet, we've provided some examples of how to use it in the servlet/ directory. clearsilver-0.10.5/java-jni/clearsilver.jar0000644001211700116100000001774210560507211015544 00000000000000PK36 META-INF/þÊPKPK36META-INF/MANIFEST.MFóMÌËLK-.Ñ K-*ÎÌϳR0Ô3àår.JM,IMÑuª ˜êĘ)h—æ)øf&åW—¤æ+xæ%ëiòrñrPKm¾ÚÖGGPK 36org/PK 36org/clearsilver/PK36org/clearsilver/HDF.class•X x\Eþ'ÙäÞÝܦIhÚæU¶¥”ÍæE+”¶)Ф¤ié#Ђ,›ä&Ù²Ù›MÛlAy•7HË[… "„$P¥ ÚòPQ^ "‚¢ òúÏÝ›ÝdsÛ®ù¾=3sæÌsæÌÜ<ù騭ò=X‚ÛÝ8wxHvHï»Bî”á]B¾'"wkø¾Ž{ ÿàTÌ vˆbÚík^\¬ #]u+ã±P¤«¾r­†jøÀÂHX§0ËIp"'%7H}a{Ø.àž•ÑþX»½Ç:Ó¨V–8+ ,Ãr›±ÅÀÉh6°-ÎÇZeöT¬àU‘ÒÔÒ/†"q3–¬ã<Äô†ú¼Vµï¨ä^_Ç7¦¶D½©kÇÛ×k¶‡:CÒð/ÿƇ¬°£ëim˜¯Ò3ãý±ˆÙáP£ q‘‹…\"äRl5p.7p®4p®6p ®5p®Öð‘ÿà¿þ‡ |‚4|jà3leØÒcv\?ãoÆ ÞŸŠÛPÛg¶‹h·¦² •-än ™ì ±ÑjçÑÍx2Òµ‰6»6ØC¹ÙÂééX¢–œÚž^Π —XS»"šÊ1T.¶hJ3”ޏ¼†¿*nvm|S´³“ye(·ò(”¦L^щ³2Ž |ÑêÈّ膈Wø›X1x¹c‹&wC刡ÏÀ7q½ÂA…E¶lµm27I|o²7¸QÈ-¸ÕÀmت)ÃP$/ R¦1íÍv¦íA)ÖªîXtCâ‰à†¢uMËF_1•Ýo‰Æ£ý‘ŽQóåû»wÕ°õ¨?K¡Ì°>¥bÕ ›‘Ù¯ÄõÛFÚÍTm{3U6_I<'2ôÙçtyeZ¡0e ‹¡Ù%îèñèHõÌ ööP¡&£wŽÃõc6$‰EÓºâÝL¬¾þ¶>›Y4Þ!Öf¹ì‚–YÉ7’EÖÒ dÛú±I­qº‹+Â%%n‰`\ò-iaáË“½lµÅ‚±Lç w‰¼‘ùcM²ÞË,K¤YR­ØÎ’âEº’£cÈgÖb²ʯD–ÙÂ%ýœû8£°Jæ!ï©pá4~E” ¥(FW3÷m¬%‰Þ)¬2Aª~9{à‘f\Õ¸^w:ò1ƒôζ&ml°m,óa/M}®m˜(Í0rýbm:`4T¬†FÖÒÔÙTÀrL ¬¤¬ºýƒÐh¬žZžoypÅçAçWÆi¹8·†¿µ8Ý8‘¼,¶‡‰ Û1aÜkŠæ”cRº=×è:]OîÙgT=Œât‹n&Ð-º\Þì6бšœÊ„"+³ï ÐÝÉD¼‹3QîçHI:@´§¤cÝC¬{‰u ÓýœùÒÿaØÔt0– ì!ö0gx÷'À²Þã¼Áö¼q`Ä)Yà*qÕ ¢´ÄU0aeÃ(_ãß…Š5C˜V5ˆƒ‹¼$ƒ˜^’3ˆ®[QjÏB¾0err¤;“ † ’;äP$× $7ÂîÌ1 gÙ ]y àtÃ’ l‡^`ì€Ç:Èû’òî„|Q%‹!cåü#rº3NÕÈ<ý.så Q="árF¨I›'PmºL]ÒZ- BÜÃo´«ô\MF…Ùo†‡1{®^¬æ„%üîb½`a81.XØÝ!<\¬m£ÛsÄí/HüÝN›âNmŠtKÂŒÝÍŒ}”£Çä¿p¼àö°$?ÎcðÙSì=ðŒòâYµÏ©6<¯6ãu^T{ñ’z/«×ðŠz¯f)¼–Չ׳ÎÅVöÇí£t>Ë}.ÛåNÙ¤dÿ^LÛ…¹kF;Š&Û[7„y»waþšŠ &aAh y4ªJ\’êG§¼™Áx‹Þ¼MoÞ¥7ï¡ïó6þüÜY†)Ùõ¶E­¡®ÏPʺ<_1^%%zCæ:@‡ò@Sy(ä«¿TåSÇDê(¤ÄF^9 >ûv-ð'JþÄCÉŸvѪ)¤›’– Ø–-Þ¯÷åÖ è¸áijiÿA±ž ª‚O£Á^<Ÿš‰ÙêP©fá(%¯§s2¾ÓÒnUGøÃ /ïÐ/g s|:Ì<ÂÌ'L=¹_I†rµý0«ÜÌ Ë’Î—9íÖq„m ì (Q¨P'â`ÕD‰¯f¬¢ñ@*–SÅ)T±’*VQÅjª8•çâ<[E“}kšxéÊËÙéò²Ô˜v©Ó‘¯ÎÀTu&f*yš}-㟔ãNZÚEKCLâÍ|ÏH2ŸÏ7 T–üƒÂ_ˆ‹¬öb»½Än/ÅV«½ —[í¸Òj¯ÂÕV{ ß$Ò^gùumµÛì–ßÎV{£ÝÞdãÝl·ü¢¶ÚÛdÌÂñ­ä炉?zÔ”þþœD¿ŠÉù6äƒè;ŸPK ³¾©Ü JPK36"org/clearsilver/CSFileLoader.classeA Â0EÿhmµºPÜzÝ\w©…B=AŒ¡¤„FÒZ<› à¡ÄÔ…Š óÿg>ïþ¸Þ¬0 0|À×x®"¯â¥ÚaÝQ ¤ø«¦],˜;wR Æ3¶SM”L½àÔ ó•î$(^Wà3íRË$P1L=cÊ:ý/öØ's©¶žŽÞ Ã2ê› ¦"}¡—÷x’vYW0œ1,={ô²¨; E“’•þ>çi5½~·SŒV=ó:Y>§º’i×Ï(¾ŠaLã; ü‡´ÔEAlM$sPxUH˜«šÈÕêʠ>i“Ýô:º%Û2ÆP=ƹًýÐúù¶_—ôúa[5EAÖ•:5„pŸÂºÆ¬u™ïíìQØ@^ŒŽã‰¤—¹&¾|Y/˜Üƒ¦„ü©öLFÒ½é?fþ|§Cý¬„‘š?éÝ8Áû5"˜ïL·\az‘´Ì·Q2[;ÈÙGN©•šÌ­  —Ñ0‡‹¦1£a3*JÊxOÃuÜÐ0%ž.!¬á6’Ö°®a ®w'ì‘i>´ «®;í‰0©d.lÔÂrÊ«$¦aŸiØÄ–†›¸ÅÍÏÚáÎ7®ê%£bÐ\…®¡‚*Çqºù«&Yd9ìèõ#ÇÒËa‹¡U¼Ð`ˆœB½ƒS0ÒIt·x —8¶Q)2ìDz÷TÂs'R/k×Sö‘U>¥íó…p±_”+ò^Ìþ×Öp1L¹Üëç|·ÿoã{R¸—åú èŒQt η˜çm›äÉô@ÓOœ­ä³’»ÄÀÉGiÁÉ’Îó-75@8Ú€UŽáÄÃÆÞb ï1ÔŸh£`t^Òâ>‡0„1G‰9&‘/·“Dv“ÏDc ø¢q¢Æßa8} 5.qýÐ N‘N#Àt‡˜ô4ÓUp¥êG­TC¢™š_$êîà É ¼û—™ÚJßÇbËŽ\! »ûMÛÅ+…Ò%I…é Òqé{ŒÈˆ ¢î3­± @*V0ŒU6àj–Û0óíˆ?c°ãe\¥ó5J¢ˆµÌïS"4K"Úþm?l`èÏfÅ$®wP=?Âãn`¸;O™ÇuV½ÆŠ×©‰··Z›9¸‘n°M‚mìÇp›š–×[#˜(jº?XÞtc›X)bí9Á¹$ÎkêD¤›½8¬óAü¯–($DqÊ<±_1êFvåD3&4+h‹ÜG Ëh»ŒöHü`ö9®ÁFÝc·Ÿ²®}þ­Swq¡®Òó>î³ ®îÑI?a›¦ tõŠýsuö%÷ØR\â”RáçSržAÉy %ç1”œ7–^>ÜioNÍŸçŒw£Ù¸!J¶åGúPK’6y‹f, PK36org/clearsilver/CSUtil.classTáRUþ.„lX¨Ri¥Æªt“)m-¶AC#èÀPüã,Ù%¹¸Ýe6†—ðúý[ÿÀ 3ê/ñ| ŸÁúÝ$q¦“ɹ÷œ=çû¾{öÜýëß_~0‹-7`jHëè™@FGS¦˜ÑGNù÷”™À}/}-ôšé-X!p¶¤ï–ÏwÜpÓÞñ1ªnd¶³nGµºÀ]Ó Âj®â¹vX—ÞæÈžO·(‘ôr–¬G$ì/˪oG ù·«š¿*|HºTìÈ-J¥ç¾ÙIuµ¨+ƒœª!B±³¨+Ó[éå VÚR ågœQ9ná=Ñ‹4þ®£ÈØüš³;㱋ûª‹ |‰‚ÀísÆRÃóÖéGnøô°âîG2ðæJAŠJ½©MµzᤤŸŠjnª¾ïVä®d@¥Õ£°QQ-Wr– À¿T€À8Þå_à&½ÄÐKËñfd‚‘ ®‚k_æâçfÁmÚx38„~¼ TjÀÒ×ü)z¶Ñke’±#ô­Ný‰ÁSÄ·“Ú1¿M¡¿4ýƲÓGÐO0Ѓï¸3J/_ÿ“}õ†à´7ioa˜jFH1AªI>™¥úÇøˆV)¾CÒk‰ø‰ú¸ndÏXkæÌjz'X:Á5˜äæß‘,bd{:{ŒÑ'±qŠ¿þññØ«—¯ÿçÒ2Ðiï‘h–x€$Rà#þæ°ÈO÷ ÅYÈc óm‰³r²¹»ûPK®H"U*PK36org/clearsilver/JNI$1.classSÛnÓ@=Û¸±ëRÒ„JÁ@h“Š&)—rI ¢HA¡TUâѱ—Ô•ãÖvE> Ò$>€B̦¨š,íÌÎÌÙ³3ã?¿~°‰ç&°<‡kXÑqÝD Ën(m›¸Š›n)㶉"îX5°f¸¤DYÇºŽ †ô¶úñ3†T©|À 5„Ç2-?ä{I¯Ãå{§'%“Ál‹Dºü•¯\Æë½fåÈ9vÿ2tùa÷ …§£j!‹E5‹ÈÞc((`5pÂnµKî&~àqɰÐIàÙ¡ˆí@8ž½fá>Xxˆ-FÖ#léxlá ž2äÔ=•ÀïHG*}'>´wl†KçÜêØ¶°z[^ÈnÕ ¸##?8æ²JÌ‹› `°šaÈe#p¢ˆGDfBóm爻1Cvâz—„ái9§Üø×éö Šyê&º#ßG|Qݧ·ÇTîôêT}§ßç¡Ç°Qjý[ zùœëwÍè é¸.¢b­V£š”ÎC cÄâtOt§¤gÐûÊ ¨¯ùiéiæ»<Þ—¢Ïe<`Xý/’”YãŸ|zµVj–`#C£J-¢¹¡EcAVŽv+¤© ˜]?û ÕŽ<ÉôØ©@—Ï i–•w÷ f¾!õáZvvˆô:ɬAbˆ¹!Ì?âó*bpá,¨pq’' dŽæiL x%ÊRÓ\ÂÒýIÀ]Z&É@}Æ/PKXõB&ƒPK36org/clearsilver/JNI$2.classmRQOAþ¦-½ã¨‚¬¨à U[@[|ム&ÄD”„ÇíÝZ×]²{Çÿâ…IôÝEœ+Ä&À&;3ûí—ovfçïù¯ß6°¡†F€{"”Ñq¿ð"ÜÅËÅa)B ÄV4 Õ×Ê¨ì ¡Üjï*=›JÂôŽ2r7ÿÑ—î³èkFÊ.7„hÏæ.‘ïT…ïw·_ŠcÁü-“hë•|Ù7›xRÃmL– BG 3è|1^dÊU2eùï[ÎYGhŒ {™c…·¹Ò©ä›™žÍu›ÅÚŠ4~VÃS°i¡M VÑ.²¬æ­t-…óJK×á§5_@¨m#]O ï¥gÑqºýC™d„úú”sQïì ŠÜ-qt$MJxÞÚ¹úîÍö5è²”MnœHé}³ÛíæZ×©Ì 3{s=7Éï#Æÿ1áx‰7w˜O3-²çr1±: (üÛêŒÙÖÿS_¡2B—ÏP:8Cù`ˆJ}âÕŸØÖC6§˜"úsEç1Ðì(õæÙWx°X‡wÄ÷S(VøPKô ’¥¨PK36org/clearsilver/JNI.classuS[OA=[ Ýn×ËM«´åÒr‰/X´XJRå‰l—…,,Ûd·%áñ*í*‰&’øà2žÙ6¥\|™o¾™3ç;ß™™?¿ÿ0ƒ• Ú1® Œ˜‚8Lˆ•I1L…0d)2bbe.€y¡Zò2€¯X” §?g¶÷Öw6$tf´S-iiöa2_¶m­`¯%„¶ßç7?í¥óùͼ„ÈfZeÇXÕ,« éÇT½>ÍEmbÙ,zIpXfÁÑœ³œvb܆l•Ó>$Ä¿bÚfé„–X|GBëjqŸÐHÖ´\ù¤`8ÛB *jûÙ©\£´vWQOì¡Nk˜ðl³”®Ø}-¨hºn¸îh*•¢1±øCŠåݪkV¶ŠeG7ÖL¡P^Ïe¦^Ež¨xŠÞ–TôcHÂÀ ÑGÛÕJ¦{`ìÇ>N;NÑQÑ…nˆ°¬â5z©±è&uËÐ×´N 'IþÑ  ÷Û6œUKs]ÃUñÑÿÀgUtˆÍö»—C‹›°SG¶)¡ã†[G·ÎÜ’qB÷ïÛÌûsÊ6†øÌÂ|§m Uœ…FE4çEvêEšÄèg;tŠã3fýŒ’8Ÿ¸„ï¢×¾:PIÖ߀–áC c¼é+ZÎ1ü¡‚¶Ýì¯ ü¿âø  ×ç7&®'^xp?IZ©r#ÌFð‹µ2Ãü6À,1KDÍQã¼ø6Ô»€,"†e®ày]B¦.¡«V8Q…¿¹œD*"DØz¤Q&JÀ[î¦YbƼ#í Í«Ñ5L¨Bº1A!!°Áùv™ZGêð> ´Òˆ/÷,“1Ú°,ï1‰+È»—V¡\!Ä™ZÅ£ ê¿B˜¹¯Š¶häVõnÞ©®°ûNŒ‘sœÌq2ŽqÝGg½}Ÿç!8†jñPK¿SS¸ºPK36 META-INF/þÊPK36m¾ÚÖGG=META-INF/MANIFEST.MFPK 36Æorg/PK 36èorg/clearsilver/PK36 ³¾©Ü Jorg/clearsilver/HDF.classPK36à¥åQ¬ö"9 org/clearsilver/CSFileLoader.classPK36’6y‹f, 5 org/clearsilver/CS.classPK36®H"U*áorg/clearsilver/CSUtil.classPK36XõB&ƒ€org/clearsilver/JNI$1.classPK36ô ’¥¨ïorg/clearsilver/JNI$2.classPK36¿SS¸ºàorg/clearsilver/JNI.classPK íßclearsilver-0.10.5/java-jni/j_neo_cgi.c0000644001211700116100000000157110261037512014604 00000000000000#include #include "CGI.h" #include "cs_config.h" #include "util/neo_err.h" #include "util/neo_misc.h" #include "util/neo_str.h" #include "util/neo_hdf.h" #include "cgi/cgi.h" #include "cgi/cgiwrap.h" #include "cgi/date.h" #include "cgi/html.h" jfieldID _cgiobjFldID = NULL; int jNeoErr (JNIEnv *env, NEOERR *err); JNIEXPORT jint JNICALL Java_CGI__1init (JNIEnv *env, jobject obj) { CGI *cgi = NULL; NEOERR *err; if (!_cgiobjFldID) { jclass objClass = (*env)->GetObjectClass(env,obj); _cgiobjFldID = (*env)->GetFieldID(env,objClass,"_cgiobj","I"); } err = cgi_init(&cgi,NULL); if (err) return jNeoErr(env,err); return (jint) cgi; } JNIEXPORT void JNICALL Java_CGI_parse (JNIEnv *env, jobject obj) { NEOERR *err; CGI *cgi = (CGI *)((*env)->GetIntField(env,obj,_cgiobjFldID)); err = cgi_parse(cgi); if (err) { jNeoErr(env,err); return; } } clearsilver-0.10.5/java-jni/j_neo_cs.c0000644001211700116100000001103110542074566014453 00000000000000#include #include #include "org_clearsilver_CS.h" #include "cs_config.h" #include "util/neo_err.h" #include "util/neo_misc.h" #include "util/neo_str.h" #include "util/neo_hdf.h" #include "cgi/cgi.h" #include "cgi/cgiwrap.h" #include "cgi/date.h" #include "cgi/html.h" #include "cs/cs.h" #include "j_neo_util.h" jfieldID _csobjFldID = NULL; static void jErr(JNIEnv *env, char *error_string) { jclass newExcCls = (*env)->FindClass(env, "java/lang/RuntimeException"); if (newExcCls == 0) { // unable to find proper class! return; } (*env)->ThrowNew(env, newExcCls, error_string); } int jNeoErr (JNIEnv *env, NEOERR *err); JNIEXPORT jint JNICALL Java_org_clearsilver_CS__1init (JNIEnv *env, jobject obj, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; CSPARSE *cs = NULL; NEOERR *err; // if (!_hdfobjFldID) { // jclass objClass = (*env)->GetObjectClass(env,obj); // _hdfobjFldID = (*env)->GetFieldID(env,objClass,"hdfptr","i"); // } err = cs_init(&cs, hdf); if (err != STATUS_OK) return jNeoErr(env,err); err = cgi_register_strfuncs(cs); if (err != STATUS_OK) return jNeoErr(env,err); return (jint) cs; } JNIEXPORT void JNICALL Java_org_clearsilver_CS__1dealloc (JNIEnv *env, jclass objClass, jint cs_obj_ptr) { CSPARSE *cs = (CSPARSE *)cs_obj_ptr; cs_destroy(&cs); } JNIEXPORT void JNICALL Java_org_clearsilver_CS__1parseFile(JNIEnv *env, jobject objCS, jint cs_obj_ptr, jstring j_filename, jboolean use_cb) { CSPARSE *cs = (CSPARSE *)cs_obj_ptr; NEOERR *err; const char *filename; FILELOAD_INFO fl_info; if (!j_filename) { return; } // throw if (use_cb == JNI_TRUE) { jclass csClass; csClass = (*env)->GetObjectClass(env, objCS); if (csClass == NULL) return; fl_info.env = env; fl_info.fl_obj = objCS; fl_info.hdf = cs->hdf; fl_info.fl_method = (*env)->GetMethodID(env, csClass, "fileLoad", "(Ljava/lang/String;)Ljava/lang/String;"); if (fl_info.fl_method == NULL) return; cs_register_fileload(cs, &fl_info, jni_fileload_cb); } filename = (*env)->GetStringUTFChars(env,j_filename,0); err = cs_parse_file(cs,(char *)filename); if (use_cb == JNI_TRUE) cs_register_fileload(cs, NULL, NULL); if (err != STATUS_OK) { jNeoErr(env,err); return; } (*env)->ReleaseStringUTFChars(env,j_filename,filename); } JNIEXPORT void JNICALL Java_org_clearsilver_CS__1parseStr (JNIEnv *env, jclass objClass, jint cs_obj_ptr, jstring j_contentstring) { CSPARSE *cs = (CSPARSE *)cs_obj_ptr; NEOERR *err; char *ms; int len; const char *contentstring; if (!j_contentstring) { return; } // throw contentstring = (*env)->GetStringUTFChars(env,j_contentstring,0); ms = strdup(contentstring); if (ms == NULL) { jErr(env, "parseStr failed"); return; } // throw error no memory len = strlen(ms); err = cs_parse_string(cs,ms,len); if (err) { jNeoErr(env,err); return; } (*env)->ReleaseStringUTFChars(env,j_contentstring,contentstring); } static NEOERR *render_cb (void *ctx, char *buf) { STRING *str= (STRING *)ctx; return nerr_pass(string_append(str, buf)); } JNIEXPORT jstring JNICALL Java_org_clearsilver_CS__1render (JNIEnv *env, jclass objClass, jint cs_obj_ptr) { CSPARSE *cs = (CSPARSE *)cs_obj_ptr; STRING str; NEOERR *err; jstring retval; int ws_strip_level = 0; int do_debug = 0; // TODO: perhaps we should pass in whether this is html as well... do_debug = hdf_get_int_value(cs->hdf, "ClearSilver.DisplayDebug", 0); ws_strip_level = hdf_get_int_value(cs->hdf, "ClearSilver.WhiteSpaceStrip", 0); string_init(&str); err = cs_render(cs, &str, render_cb); if (err) { string_clear(&str); jNeoErr(env,err); return NULL; } if (ws_strip_level) { cgi_html_ws_strip(&str, ws_strip_level); } if (do_debug) { do { err = string_append (&str, "
"); if (err != STATUS_OK) break; err = string_append (&str, "
");
      if (err != STATUS_OK) break;
      err = hdf_dump_str (cs->hdf, NULL, 0, &str);
      if (err != STATUS_OK) break;
      err = string_append (&str, "
"); if (err != STATUS_OK) break; } while (0); if (err) { string_clear(&str); jNeoErr(env,err); return NULL; } } retval = (*env)->NewStringUTF(env, str.buf); string_clear(&str); return retval; } // Change global HDF JNIEXPORT void JNICALL Java_org_clearsilver_CS__1setGlobalHdf (JNIEnv *env, jobject objclass, jint cs_obj_ptr, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; CSPARSE *cs = (CSPARSE *)cs_obj_ptr; cs->global_hdf = hdf; } clearsilver-0.10.5/java-jni/j_neo_util.c0000644001211700116100000003220110542074552015020 00000000000000#include #include #include "org_clearsilver_HDF.h" #include "cs_config.h" #include "util/neo_err.h" #include "util/neo_misc.h" #include "util/neo_str.h" #include "util/neo_hdf.h" #include "cgi/cgi.h" #include "cgi/cgiwrap.h" #include "cgi/date.h" #include "cgi/html.h" #include "j_neo_util.h" void throwException(JNIEnv *env, const char* class_name, const char *message) { jclass ex_class = (*env)->FindClass(env, class_name); if (ex_class == NULL) { // Unable to find proper class! return; } (*env)->ThrowNew(env, ex_class, message); } void throwNullPointerException(JNIEnv *env, const char *message) { throwException(env, "java/lang/NullPointerException", message); } void throwRuntimeException(JNIEnv *env, const char *message) { throwException(env, "java/lang/RuntimeException", message); } void throwIOException(JNIEnv *env, const char *message) { throwException(env, "java/io/IOException", message); } void throwFileNotFoundException(JNIEnv *env, const char *message) { throwException(env, "java/io/FileNotFoundException", message); } void throwOutOfMemoryError(JNIEnv *env, const char *message) { throwException(env, "java/lang/OutOfMemoryError", message); } // Throws a runtime exception back to the Java VM appropriate for the type of // error and frees the NEOERR that is passed in. // TODO: throw more specific exceptions for errors like NERR_IO and NERR_NOMEM int jNeoErr(JNIEnv *env, NEOERR *err) { STRING str; string_init(&str); if (nerr_match(err, NERR_PARSE)) { nerr_error_string(err, &str); throwRuntimeException(env, str.buf); } else if (nerr_match(err, NERR_IO)) { nerr_error_string(err, &str); throwIOException(env, str.buf); } else if (nerr_match(err, NERR_NOMEM)) { nerr_error_string(err, &str); throwOutOfMemoryError(env, str.buf); } else { nerr_error_traceback(err, &str); throwRuntimeException(env, str.buf); } nerr_ignore(&err); // free err, otherwise it would leak string_clear(&str); return 0; } JNIEXPORT jint JNICALL Java_org_clearsilver_HDF__1init( JNIEnv *env, jclass objClass) { HDF *hdf = NULL; NEOERR *err; err = hdf_init(&hdf); if (err != STATUS_OK) { return jNeoErr(env, err); } return (jint) hdf; } JNIEXPORT void JNICALL Java_org_clearsilver_HDF__1dealloc( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; hdf_destroy(&hdf); } JNIEXPORT jint JNICALL Java_org_clearsilver_HDF__1getIntValue( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdfname, jint default_value) { HDF *hdf = (HDF *)hdf_obj_ptr; int r; const char *hdfname; if (!j_hdfname) { throwNullPointerException(env, "hdfname argument was null"); return 0; } hdfname = (*env)->GetStringUTFChars(env,j_hdfname, 0); r = hdf_get_int_value(hdf, hdfname, default_value); (*env)->ReleaseStringUTFChars(env,j_hdfname,hdfname); return r; } JNIEXPORT jstring JNICALL Java_org_clearsilver_HDF__1getValue( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdfname, jstring j_default_value) { HDF *hdf = (HDF *)hdf_obj_ptr; const char *r; const char *hdfname; const char *default_value; jstring retval; if (!j_hdfname) { throwNullPointerException(env, "hdfname argument was null"); return 0; } hdfname = (*env)->GetStringUTFChars(env,j_hdfname,0); if (!j_default_value) { default_value = NULL; } else { default_value = (*env)->GetStringUTFChars(env, j_default_value, 0); } r = hdf_get_value(hdf, hdfname, default_value); (*env)->ReleaseStringUTFChars(env, j_hdfname, hdfname); retval = (r ? (*env)->NewStringUTF(env, r) : 0); if (default_value) { (*env)->ReleaseStringUTFChars(env, j_default_value, default_value); } return retval; } JNIEXPORT void JNICALL Java_org_clearsilver_HDF__1setValue( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdfname, jstring j_value) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *hdfname; const char *value; if (!j_hdfname) { throwNullPointerException(env, "hdfname argument was null"); return; } hdfname = (*env)->GetStringUTFChars(env, j_hdfname, 0); if (j_value) { value = (*env)->GetStringUTFChars(env, j_value, 0); } else { value = NULL; } err = hdf_set_value(hdf, hdfname, value); (*env)->ReleaseStringUTFChars(env, j_hdfname, hdfname); if (value) { (*env)->ReleaseStringUTFChars(env, j_value, value); } if (err != STATUS_OK) { // Throw an exception jNeoErr(env, err); } } JNIEXPORT void JNICALL Java_org_clearsilver_HDF__1removeTree( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdfname) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *hdfname; if (!j_hdfname) { throwNullPointerException(env, "hdfname argument was null"); return; } hdfname = (*env)->GetStringUTFChars(env, j_hdfname, 0); err = hdf_remove_tree(hdf, hdfname); (*env)->ReleaseStringUTFChars(env, j_hdfname, hdfname); if (err != STATUS_OK) { // Throw an exception jNeoErr(env, err); } } JNIEXPORT void JNICALL Java_org_clearsilver_HDF__1setSymLink( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdf_name_src, jstring j_hdf_name_dest) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *hdf_name_src; const char *hdf_name_dest; if (!j_hdf_name_src) { throwNullPointerException(env, "hdf_name_src argument was null"); return; } hdf_name_src = (*env)->GetStringUTFChars(env, j_hdf_name_src, 0); if (!j_hdf_name_dest) { throwNullPointerException(env, "hdf_name_dest argument was null"); return; } hdf_name_dest = (*env)->GetStringUTFChars(env, j_hdf_name_dest, 0); err = hdf_set_symlink(hdf, hdf_name_src, hdf_name_dest); (*env)->ReleaseStringUTFChars(env, j_hdf_name_src, hdf_name_src); (*env)->ReleaseStringUTFChars(env, j_hdf_name_dest, hdf_name_dest); if (err != STATUS_OK) { // Throw an exception jNeoErr(env, err); } } JNIEXPORT jstring JNICALL Java_org_clearsilver_HDF__1dump( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; STRING str; jstring retval; string_init(&str); err = hdf_dump_str(hdf, NULL, 0, &str); if (err != STATUS_OK) { // Throw an exception jNeoErr(env, err); retval = NULL; } else { retval = (*env)->NewStringUTF(env,str.buf); } string_clear(&str); return retval; } NEOERR *jni_fileload_cb(void *ctx, HDF *hdf, const char *filename, char **contents) { FILELOAD_INFO *info = (FILELOAD_INFO *)ctx; jstring filename_str; jstring loaded_string; const char *c_loaded_string; // We assume that the hdf passed back is actually the hdf we already // have... if (hdf != info->hdf) return nerr_raise(NERR_ASSERT, "jni_fileload_cb: passed HDF pointer doesn't match hdf_obj_ptr"); filename_str = (*info->env)->NewStringUTF(info->env, filename); (*info->env)->NewLocalRef(info->env, filename_str); loaded_string = (*info->env)->CallObjectMethod(info->env, info->fl_obj, info->fl_method, filename_str); if ((*info->env)->ExceptionCheck(info->env)) { (*info->env)->ExceptionDescribe(info->env); (*info->env)->ExceptionClear(info->env); return nerr_raise(NERR_ASSERT, "jni_fileload_cb: HDF.fileLoad returned exception, see STDERR"); } c_loaded_string = (*info->env)->GetStringUTFChars(info->env, loaded_string, 0); if (c_loaded_string) { *contents = strdup(c_loaded_string); } (*info->env)->ReleaseStringUTFChars(info->env, loaded_string, c_loaded_string); return STATUS_OK; } JNIEXPORT jboolean JNICALL Java_org_clearsilver_HDF__1readFile( JNIEnv *env, jobject objClass, jint hdf_obj_ptr, jstring j_filename, jboolean use_cb) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *filename; jboolean retval; FILELOAD_INFO fl_info; if (use_cb == JNI_TRUE) { jclass hdfClass; fl_info.env = env; fl_info.fl_obj = objClass; fl_info.hdf = hdf; hdfClass = (*env)->GetObjectClass(env, objClass); if (hdfClass == NULL) return JNI_FALSE; fl_info.fl_method = (*env)->GetMethodID(env, hdfClass, "fileLoad", "(Ljava/lang/String;)Ljava/lang/String;"); if (fl_info.fl_method == NULL) return JNI_FALSE; hdf_register_fileload(hdf, &fl_info, jni_fileload_cb); } filename = (*env)->GetStringUTFChars(env, j_filename, 0); err = hdf_read_file(hdf, filename); (*env)->ReleaseStringUTFChars(env, j_filename, filename); if (use_cb == JNI_TRUE) hdf_register_fileload(hdf, NULL, NULL); if (err != STATUS_OK) { // Throw an exception. jNeoErr handles all types of errors other than // NOT_FOUND, since that can mean different things in different contexts. // In this context, it means "file not found". if (nerr_match(err, NERR_NOT_FOUND)) { STRING str; string_init(&str); nerr_error_string(err, &str); throwFileNotFoundException(env, str.buf); string_clear(&str); } else { jNeoErr(env, err); } } retval = (err == STATUS_OK); return retval; } JNIEXPORT jboolean JNICALL Java_org_clearsilver_HDF__1writeFile( JNIEnv *env, jobject objClass, jint hdf_obj_ptr, jstring j_filename) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *filename; jboolean retval; filename = (*env)->GetStringUTFChars(env, j_filename, 0); err = hdf_write_file(hdf, filename); (*env)->ReleaseStringUTFChars(env, j_filename, filename); if (err != STATUS_OK) { jNeoErr(env, err); } retval = (err == STATUS_OK); return retval; } JNIEXPORT jboolean JNICALL Java_org_clearsilver_HDF__1writeFileAtomic( JNIEnv *env, jobject objClass, jint hdf_obj_ptr, jstring j_filename) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *filename; jboolean retval; filename = (*env)->GetStringUTFChars(env, j_filename, 0); err = hdf_write_file_atomic(hdf, filename); (*env)->ReleaseStringUTFChars(env, j_filename, filename); if (err != STATUS_OK) { jNeoErr(env, err); } retval = (err == STATUS_OK); return retval; } JNIEXPORT jboolean JNICALL Java_org_clearsilver_HDF__1readString( JNIEnv *env, jobject objClass, jint hdf_obj_ptr, jstring j_data) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; const char *data; jboolean retval; data = (*env)->GetStringUTFChars(env, j_data, 0); err = hdf_read_string(hdf, data); (*env)->ReleaseStringUTFChars(env, j_data, data); if (err != STATUS_OK) { jNeoErr(env, err); } retval = (err == STATUS_OK); return retval; } JNIEXPORT jstring JNICALL Java_org_clearsilver_HDF__1writeString( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; NEOERR *err; char *output = NULL; jstring retval = NULL; err = hdf_write_string(hdf, &output); if (err != STATUS_OK) { jNeoErr(env, err); } else if (output) { retval = (*env)->NewStringUTF(env, output); free(output); } return retval; } JNIEXPORT jint JNICALL Java_org_clearsilver_HDF__1getObj( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdf_path) { HDF *hdf = (HDF *)hdf_obj_ptr; HDF *obj_hdf = NULL; const char *hdf_path; hdf_path = (*env)->GetStringUTFChars(env, j_hdf_path, 0); obj_hdf = hdf_get_obj(hdf, (char*)hdf_path); (*env)->ReleaseStringUTFChars(env, j_hdf_path, hdf_path); return (jint)obj_hdf; } JNIEXPORT jint JNICALL Java_org_clearsilver_HDF__1getChild( JNIEnv *env, jclass objClass, jint hdf_obj_ptr, jstring j_hdf_path) { HDF *hdf = (HDF *)hdf_obj_ptr; HDF *obj_hdf = NULL; const char *hdf_path; hdf_path = (*env)->GetStringUTFChars(env, j_hdf_path, 0); obj_hdf = hdf_get_child(hdf, (char*)hdf_path); (*env)->ReleaseStringUTFChars(env, j_hdf_path, hdf_path); return (jint)obj_hdf; } JNIEXPORT jint JNICALL Java_org_clearsilver_HDF__1objChild( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; HDF *child_hdf = NULL; child_hdf = hdf_obj_child(hdf); return (jint)child_hdf; } JNIEXPORT jint JNICALL Java_org_clearsilver_HDF__1objNext( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; HDF *next_hdf = NULL; next_hdf = hdf_obj_next(hdf); return (jint)next_hdf; } JNIEXPORT jstring JNICALL Java_org_clearsilver_HDF__1objName( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; char *name; jstring retval = NULL; name = hdf_obj_name(hdf); if (name != NULL) { retval = (*env)->NewStringUTF(env, name); } return retval; } JNIEXPORT jstring JNICALL Java_org_clearsilver_HDF__1objValue( JNIEnv *env, jclass objClass, jint hdf_obj_ptr) { HDF *hdf = (HDF *)hdf_obj_ptr; char *name; jstring retval = NULL; name = hdf_obj_value(hdf); if (name != NULL) { retval = (*env)->NewStringUTF(env, name); } return retval; } JNIEXPORT void JNICALL Java_org_clearsilver_HDF__1copy (JNIEnv *env, jclass objClass, jint hdf_dest_ptr, jstring j_hdf_path, jint hdf_src_ptr) { HDF *dest = (HDF *)hdf_dest_ptr; HDF *src = (HDF *)hdf_src_ptr; const char *hdf_path; hdf_path = (*env)->GetStringUTFChars(env, j_hdf_path, 0); hdf_copy(dest, hdf_path, src); (*env)->ReleaseStringUTFChars(env, j_hdf_path, hdf_path); } clearsilver-0.10.5/java-jni/j_neo_util.h0000644001211700116100000000071710541657051015034 00000000000000// Copyright 2006 Brandon Long // All Rights Reserved. // // This code is made available under the terms of the ClearSilver License. // http://www.clearsilver.net/license.hdf #ifndef __J_NEO_UTIL_H_ #define __J_NEO_UTIL_H_ 1 typedef struct _fileload_info { JNIEnv *env; jobject fl_obj; HDF *hdf; jmethodID fl_method; } FILELOAD_INFO; NEOERR *jni_fileload_cb(void *ctx, HDF *hdf, const char *filename, char **contents); #endif // __J_NEO_UTIL_H_ clearsilver-0.10.5/java-jni/javatest.gold0000644001211700116100000000746310541664165015235 00000000000000Testing HDF set and dump Foo.Bar = 10 Foo.Baz = 20 Testing HDF get 10 20 ---- Testing HDF setSymLink 20 ---- Testing HDF get where default value is null foo = 10 foo = null ---- Testing HDF get int 10 ---- Testing HDF parse/render Foo.Bar: Foo.Baz: ---- Foo.Bar:10 Foo.Baz:20 Testing registered string functions Foo.Bar:10 Foo.Baz:20 abc%26+231%3C%3E%2F%3F abc& 231<>/? Testing white space stripping 10 This is a string without whitespace stripped 10 This is a string without whitespace stripped Testing debug dump 10 This is a string without whitespace stripped
Foo.Bar = 10
Foo.Baz = 20
Foo.Baz2 : Foo.Baz
Foo.EscapeTest = abc& 231<>/?
ClearSilver.WhiteSpaceStrip = 1
ClearSilver.DisplayDebug = 1
Final HDF dump Foo.Bar = 10 Foo.Baz = 20 Foo.Baz2 : Foo.Baz Foo.EscapeTest = abc& 231<>/? ClearSilver.WhiteSpaceStrip = 1 ClearSilver.DisplayDebug = 1 Testing HDF.readFile() Foo.Bar = 10 Foo.Baz = 20 Testing HDF.readFile() for a file that doesn't exist Caught exception of type java.io.FileNotFoundException Testing HDF.writeFile() Testing HDF.writeString() Foo { Bar = 10 Baz = 20 } Testing HDF.getObj() Bar = 10 Baz = 20 Testing HDF.objName() Should be "Foo": Foo Should be "Bar": Bar Should be null: null Testing HDF.objValue() Value of Foo.Bar: 10 Value of root node: null Testing HDF.objChild() First child name: Bar Testing HDF.objNext() Next child name: Baz Next child (should be null): null Testing HDF.copy() name should be barneyb: barneyb Testing HDF.exportDate() DatePST.sec = 18 DatePST.min = 50 DatePST.24hour = 19 DatePST.hour = 7 DatePST.am = 0 DatePST.mday = 13 DatePST.mon = 3 DatePST.year = 2006 DatePST.2yr = 06 DatePST.wday = 2 DatePST.tzoffset = -0800 DateEST.sec = 18 DateEST.min = 50 DateEST.24hour = 22 DateEST.hour = 10 DateEST.am = 0 DateEST.mday = 13 DateEST.mon = 3 DateEST.year = 2006 DateEST.2yr = 06 DateEST.wday = 2 DateEST.tzoffset = -0500 Testing escape mode: html Config.VarEscapeMode = "html" Some.HTML = Default HTML escaping: ---- Default HTML escaping: <script src="some.js">alert('123');</script> Testing escape mode: js Config.VarEscapeMode = "js" Some.HTML = Default JS escaping: ---- Default JS escaping: \x3Cscript src=\x22some.js\x22\x3Ealert(\x27123\x27)\x3B\x3C\x2Fscript\x3E Testing escape mode: url Config.VarEscapeMode = "url" Some.HTML = Default URL escaping: ---- Default URL escaping: %3Cscript+src%3D%22some.js%22%3Ealert(%27123%27)%3B%3C%2Fscript%3E Testing escape blocks: none Config.VarEscapeMode = "none" Some.HTML = url escape block: js escape block: html escape block: ---- url escape block: %3Cscript+src%3D%22some.js%22%3Ealert(%27123%27)%3B%3C%2Fscript%3E js escape block: \x3Cscript src=\x22some.js\x22\x3Ealert(\x27123\x27)\x3B\x3C\x2Fscript\x3E html escape block: <script src="some.js">alert('123');</script> Testing HDF.readFile() with callback CSTestLoader::Load testdata/test1.hdf ---- file begin ---- # Simple HDF file to test that HDF.readFile() works Foo.Bar = 10 Foo.Baz = 20 ---- file end ---- Foo.Bar = 10 Foo.Baz = 20 Testing CS.parseFile() with callback CSTestLoader::Load testdata/test.cs ---- file begin ---- Testing CS parse file... ---- file end ---- Testing CS parse file... 10 20 Beans clearsilver-0.10.5/java-jni/servlet/0000755001211700116100000000000010645505045014273 500000000000000clearsilver-0.10.5/java-jni/servlet/CSPage.java0000644001211700116100000000603310261037512016153 00000000000000/* $Id: CSPage.java,v 1.1 2002/09/20 23:14:10 jeske Exp $ * */ import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.lang.String.*; import org.clearsilver.*; /** * The simplest possible servlet. * */ public class CSPage extends HttpServlet { public HDF hdf; public CS cs; public boolean page_debug = true; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); hdf = new HDF(); cs = new CS(hdf); // HTTP headers Enumeration e = request.getHeaderNames(); while (e.hasMoreElements()) { String headerName = (String)e.nextElement(); String headerValue = request.getHeader(headerName); hdf.setValue("HTTP." + headerName,headerValue); } hdf.setValue("HTTP.PATH_INFO",request.getPathInfo()); hdf.setValue("CGI.QueryString",request.getQueryString()); hdf.setValue("CGI.RequestMethod",request.getMethod()); // Querystring paramaters e = request.getParameterNames(); while (e.hasMoreElements()) { String paramName = (String)e.nextElement(); String paramValue = request.getParameter(paramName); hdf.setValue("Query." + paramName,paramValue); } // Cookies Cookie[] cookies = request.getCookies(); if (cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; hdf.setValue("Cookie." + cookie.getName(),cookie.getValue()); } } // CGI example // check for Actions // then call display method this.display(); // run required page template through CS // cs.parseFile(a_template_file); // Page Output /* first do cookies String cookieName = request.getParameter("cookiename"); String cookieValue = request.getParameter("cookievalue"); if (cookieName != null && cookieValue != null) { Cookie cookie = new Cookie(cookieName, cookieValue); response.addCookie(cookie); out.println("

"); out.println(rb.getString("cookies.set") + "
"); out.print(rb.getString("cookies.name") + " " + cookieName + "
"); out.print(rb.getString("cookies.value") + " " + cookieValue); } */ response.setContentType("text/html"); out.print(cs.render()); // debug if (page_debug) { out.print("


");
	  out.print(hdf.dump());
	  out.print("
"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } public void display() { hdf.setValue("Foo.Bar","1"); cs.parseStr("Hello Clearsilver

Foo.Bar
"); } } clearsilver-0.10.5/java-jni/servlet/HelloCSServlet.java0000644001211700116100000000143210261037512017705 00000000000000/* $Id: HelloCSServlet.java,v 1.1 2002/09/20 22:13:08 jeske Exp $ * */ import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.clearsilver.*; /** * The simplest possible Clearsilver servlet. * */ public class HelloCSServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); HDF hdf = new HDF(); hdf.setValue("Foo.Bar","1"); CS cs = new CS(hdf); cs.parseStr("Hello Clearsilver

Foo.Bar: "); response.setContentType("text/html"); out.print(cs.render()); } } clearsilver-0.10.5/java-jni/testdata/0000755001211700116100000000000010645505045014420 500000000000000clearsilver-0.10.5/java-jni/testdata/test.cs0000644001211700116100000000015610541663703015651 00000000000000Testing CS parse file... clearsilver-0.10.5/java-jni/testdata/test1.hdf0000644001211700116100000000011610261037512016052 00000000000000# Simple HDF file to test that HDF.readFile() works Foo.Bar = 10 Foo.Baz = 20 clearsilver-0.10.5/perl/0000755001211700116100000000000010645505045012052 500000000000000clearsilver-0.10.5/perl/Changes0000644001211700116100000000037210261037512013260 00000000000000Revision history for Perl extension ClearSilver. 0.02 Mon Sep 2 - Added sortObj() method to HDF class. - Filled in README. 0.01 Wed Aug 14 17:10:52 2002 - original version; created by h2xs 1.21 with options -A -n ClearSilver clearsilver-0.10.5/perl/ClearSilver.pm0000644001211700116100000000227310261037512014540 00000000000000package ClearSilver; use 5.006; use strict; use warnings; require Exporter; require DynaLoader; our @ISA = qw(Exporter DynaLoader); # Items to export into callers namespace by default. Note: do not export # names by default without a very good reason. Use EXPORT_OK instead. # Do not simply export all your public functions/methods/constants. # This allows declaration use ClearSilver ':all'; # If you do not need this, moving things directly into @EXPORT or @EXPORT_OK # will save memory. our %EXPORT_TAGS = ( 'all' => [ qw( ) ] ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } ); our @EXPORT = qw( ); our $VERSION = '0.01'; bootstrap ClearSilver $VERSION; # Preloaded methods go here. 1; __END__ # Below is stub documentation for your module. You better edit it! =head1 NAME ClearSilver - Perl extension for blah blah blah =head1 SYNOPSIS use ClearSilver; blah blah blah =head1 DESCRIPTION Stub documentation for ClearSilver, created by h2xs. It looks like the author of the extension was negligent enough to leave the stub unedited. Blah blah blah. =head2 EXPORT None by default. =head1 AUTHOR A. U. Thor, Ea.u.thor@a.galaxy.far.far.awayE =head1 SEE ALSO L. =cut clearsilver-0.10.5/perl/ClearSilver.xs0000644001211700116100000001723010645302166014563 00000000000000#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ClearSilver.h" /* #define DEBUG_MODE 1 */ typedef struct { HDF* hdf; NEOERR* err; } perlHDF; typedef struct { CSPARSE* cs; NEOERR* err; } perlCS; typedef perlHDF* ClearSilver__HDF; typedef perlCS* ClearSilver__CS; static char* g_sort_func_name; static void debug(char* fmt, ...) { #ifdef DEBUG_MODE va_list argp; va_start(argp, fmt); vprintf(fmt, argp); va_end(argp); #endif } static NEOERR *output (void *ctx, char *s) { sv_catpv((SV*)ctx, s); return STATUS_OK; } static int sortFunction(const void* in_a, const void* in_b) { HDF** hdf_a; HDF** hdf_b; perlHDF a, b; SV* sv_a; SV* sv_b; int count; int ret; dSP; hdf_a = (HDF**)in_a; hdf_b = (HDF**)in_b; /* convert to a type Perl can access */ a.hdf = *hdf_a; a.err = STATUS_OK; b.hdf = *hdf_b; b.err = STATUS_OK; ENTER; SAVETMPS; PUSHMARK(SP); sv_a = sv_newmortal(); sv_setref_pv(sv_a, "ClearSilver::HDF", (void*)&a); sv_b = sv_newmortal(); sv_setref_pv(sv_b, "ClearSilver::HDF", (void*)&b); XPUSHs(sv_a); XPUSHs(sv_b); PUTBACK; count = call_pv(g_sort_func_name, G_SCALAR); SPAGAIN; if (count != 1) croak("Big trouble\n"); PUTBACK; ret = POPi; FREETMPS; LEAVE; return ret; } MODULE = ClearSilver PACKAGE = ClearSilver::HDF PREFIX = perlhdf_ ClearSilver::HDF perlhdf_new(self) char* self PREINIT: ClearSilver__HDF hdf; CODE: debug("%s\n", self); hdf = (ClearSilver__HDF)malloc(sizeof(perlHDF)); if (!hdf) { RETVAL = NULL; } else { hdf->err = hdf_init(&(hdf->hdf)); RETVAL = hdf; } OUTPUT: RETVAL void perlhdf_DESTROY(hdf) ClearSilver::HDF hdf; CODE: debug("hdf_DESTROY:%x\n", hdf); hdf_destroy(&(hdf->hdf)); int perlhdf_setValue(hdf, key, value) ClearSilver::HDF hdf char* key char* value CODE: hdf->err = hdf_set_value(hdf->hdf, key, value); if (hdf->err == STATUS_OK) { RETVAL = 0; } else { RETVAL = 1; } OUTPUT: RETVAL char* perlhdf_getValue(hdf, key, default_value) ClearSilver::HDF hdf char* key char* default_value CODE: RETVAL = hdf_get_value(hdf->hdf, key, default_value); OUTPUT: RETVAL int perlhdf_copy(hdf, name, src); ClearSilver::HDF hdf char* name ClearSilver::HDF src CODE: hdf->err = hdf_copy(hdf->hdf, name, src->hdf); if (hdf->err == STATUS_OK) { RETVAL = 0; } else { RETVAL = 1; } OUTPUT: RETVAL int perlhdf_readFile(hdf, filename) ClearSilver::HDF hdf char* filename CODE: hdf->err = hdf_read_file(hdf->hdf, filename); if (hdf->err == STATUS_OK) { RETVAL = 1; } else { RETVAL = 0; } OUTPUT: RETVAL int perlhdf_writeFile(hdf, filename) ClearSilver::HDF hdf char* filename CODE: hdf->err = hdf_write_file(hdf->hdf, filename); if (hdf->err == STATUS_OK) { RETVAL = 1; } else { RETVAL = 0; } OUTPUT: RETVAL ClearSilver::HDF perlhdf_getObj(hdf, name) ClearSilver::HDF hdf; char* name PREINIT: HDF* tmp_hdf; perlHDF* perlhdf; CODE: do { tmp_hdf = hdf_get_obj(hdf->hdf, name); if (!tmp_hdf) { RETVAL = NULL; break; } perlhdf = (perlHDF*)malloc(sizeof(perlHDF)); if (!perlhdf) { RETVAL = NULL; break; } perlhdf->hdf = tmp_hdf; perlhdf->err = STATUS_OK; RETVAL = perlhdf; } while (0); OUTPUT: RETVAL ClearSilver::HDF perlhdf_objChild(hdf) ClearSilver::HDF hdf; PREINIT: HDF* tmp_hdf; perlHDF* child; CODE: do { tmp_hdf = hdf_obj_child(hdf->hdf); if (!tmp_hdf) { RETVAL = NULL; break; } child = (perlHDF*)malloc(sizeof(perlHDF)); if (!child) { RETVAL = NULL; break; } child->hdf = tmp_hdf; child->err = STATUS_OK; RETVAL = child; } while (0); OUTPUT: RETVAL ClearSilver::HDF perlhdf_getChild(hdf, name) ClearSilver::HDF hdf; char* name; PREINIT: HDF* tmp_hdf; perlHDF* child; CODE: do { tmp_hdf = hdf_get_child(hdf->hdf, name); if (!tmp_hdf) { RETVAL = NULL; break; } child = (perlHDF*)malloc(sizeof(perlHDF)); if (!child) { RETVAL = NULL; break; } child->hdf = tmp_hdf; child->err = STATUS_OK; RETVAL = child; } while (0); OUTPUT: RETVAL char* perlhdf_objValue(hdf) ClearSilver::HDF hdf; CODE: RETVAL = hdf_obj_value(hdf->hdf); OUTPUT: RETVAL char* perlhdf_objName(hdf) ClearSilver::HDF hdf; CODE: RETVAL = hdf_obj_name(hdf->hdf); OUTPUT: RETVAL ClearSilver::HDF perlhdf_objNext(hdf) ClearSilver::HDF hdf; PREINIT: HDF* tmp_hdf; perlHDF* next; CODE: do { tmp_hdf = hdf_obj_next(hdf->hdf); if (!tmp_hdf) { RETVAL = NULL; break; } next = (perlHDF*)malloc(sizeof(perlHDF)); if (!next) { RETVAL = NULL; break; } next->hdf = tmp_hdf; next->err = STATUS_OK; RETVAL = next; } while (0); OUTPUT: RETVAL int perlhdf_sortObj(hdf, func_name) ClearSilver::HDF hdf; char* func_name; PREINIT: NEOERR* err; CODE: g_sort_func_name = func_name; err = hdf_sort_obj(hdf->hdf, sortFunction); RETVAL = 0; OUTPUT: RETVAL int perlhdf_setSymlink(hdf, src, dest) ClearSilver::HDF hdf; char* src; char* dest; PREINIT: NEOERR* err; CODE: err = hdf_set_symlink (hdf->hdf, src, dest); if (err == STATUS_OK) { RETVAL = 1; } else { RETVAL = 0; } OUTPUT: RETVAL int perlhdf_removeTree(hdf, name) ClearSilver::HDF hdf; char* name; PREINIT: NEOERR* err; CODE: err = hdf_remove_tree(hdf->hdf, name); if (err == STATUS_OK) { RETVAL = 1; } else { RETVAL = 0; } OUTPUT: RETVAL MODULE = ClearSilver PACKAGE = ClearSilver::CS PREFIX = perlcs_ ClearSilver::CS perlcs_new(self, hdf) char* self ClearSilver::HDF hdf; PREINIT: perlCS* cs; CODE: cs = (perlCS*)malloc(sizeof(perlCS)); if (!cs) { RETVAL = NULL; } else { cs->err = cs_init(&(cs->cs), hdf->hdf); if (cs->err == STATUS_OK) { cs->err = cgi_register_strfuncs(cs->cs); } RETVAL = cs; } OUTPUT: RETVAL void perlcs_DESTROY(cs) ClearSilver::CS cs; CODE: debug("perlcs_DESTROY() is called\n"); cs_destroy(&(cs->cs)); void perlcs_displayError(cs) ClearSilver::CS cs; CODE: nerr_log_error(cs->err); char * perlcs_render(cs) ClearSilver::CS cs CODE: { SV *str = newSV(0); cs->err = cs_render(cs->cs, str, output); if (cs->err == STATUS_OK) { ST(0) = sv_2mortal(str); } else { SvREFCNT_dec(str); ST(0) = &PL_sv_undef; } XSRETURN(1); } int perlcs_parseFile(cs, cs_file) ClearSilver::CS cs char* cs_file CODE: do { cs->err = cs_parse_file(cs->cs, cs_file); if (cs->err != STATUS_OK) { cs->err = nerr_pass(cs->err); RETVAL = 0; break; } RETVAL = 1; } while (0); OUTPUT: RETVAL int perlcs_parseString(cs, in_str) ClearSilver::CS cs char* in_str PREINIT: char* cs_str; int len; CODE: do { len = strlen(in_str); cs_str = (char *)malloc(len); if (!cs_str) { RETVAL = 0; break; } strcpy(cs_str, in_str); cs->err = cs_parse_string(cs->cs, cs_str, len); if (cs->err != STATUS_OK) RETVAL = 0; RETVAL = 1; } while (0); OUTPUT: RETVAL clearsilver-0.10.5/perl/MANIFEST0000644001211700116100000000014610261037512013115 00000000000000Changes ClearSilver.pm ClearSilver.xs typemap Makefile.PL MANIFEST README test.pl test.hdf test.gold clearsilver-0.10.5/perl/Makefile.PL0000644001211700116100000000154610336773714013761 00000000000000use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'ClearSilver', 'VERSION_FROM' => 'ClearSilver.pm', # finds $VERSION 'PREREQ_PM' => {}, # e.g., Module::Name => 1.1 ($] >= 5.005 ? ## Add these new keywords supported since 5.005 (ABSTRACT_FROM => 'ClearSilver.pm', # retrieve abstract from module AUTHOR => 'A. U. Thor ') : ()), # TODO: don't include -lz if we aren't depending on it 'LIBS' => ['-L../libs -lneo_cgi -lneo_cs -lneo_utl -lz'], 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' # Insert -I. if you add *.h files later: 'INC' => '-I../', # Un-comment this if you add C files to link with later: # 'OBJECT' => '$(O_FILES)', # link all the C files too ); clearsilver-0.10.5/perl/README0000644001211700116100000000226410261037512012647 00000000000000ClearSilver version 0.02 ======================== The README is used to introduce the module and provide instructions on how to install the module, any machine dependencies it may have (for example C compilers and installed libraries) and any other information that should be provided before the module is installed. A README file is required for CPAN modules since CPAN extracts the README file from a module distribution so that people browsing the archive can use it get an idea of the modules uses. It is usually a good idea to provide version information here so that people can decide whether fixes for the module are worth downloading. INSTALLATION This Perl module is supposed to be put under ClearSilver's top directory as perl/. To install this module type the following: cd perl/ perl Makefile.PL make make test sudo make install DEPENDENCIES This module requires these other modules and libraries: libneo_cgi.a libneo_cs.a libneo_utl.a COPYRIGHT AND LICENCE This Perl module can be distributed under GPL version 2, or under the Neotonic ClearSilver License Copyright (C) 2002 Gaku Ueda More up-to-date information available from: http://www.gaku.net/cs/en/ clearsilver-0.10.5/perl/test.cs0000644001211700116100000000021310261037512013265 00000000000000 clearsilver-0.10.5/perl/test.gold0000644001211700116100000000005110261037512013605 00000000000000value3 value1 value1 value2 value3 clearsilver-0.10.5/perl/test.hdf0000644001211700116100000000022010261037512013417 00000000000000 TopNode.2nd1.Entry1 = value1 TopNode.2nd1 { Entry2 = value2 Entry3 = value3 } Sort.Data { entry1 = 200 entry2 = 144 entry3 = 3 } clearsilver-0.10.5/perl/test.pl0000644001211700116100000000703410344025474013311 00000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl test.pl' ######################### # change 'tests => 1' to 'tests => last_test_to_print'; sub result { my($i, $state) = @_; if ($state) { print "ok $i\n"; } else { print "ng $i\n"; exit $i; } } sub sortFunc { my($a, $b) = @_; my($va, $vb); $va = $a->objValue(); $vb = $b->objValue(); return $va <=> $vb; } use Test; BEGIN { plan tests => 13 }; use ClearSilver; ok(1); # If we made it this far, we're ok. $testnum = 2; # # test new() # $hdf = ClearSilver::HDF->new(); $hdf ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test reading file # $ret = $hdf->readFile("test.hdf"); $ret ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test getObj() # $lev2_node = $hdf->getObj("TopNode.2nd1"); $lev2_node ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test objName() # $lev2_name = $lev2_node->objName(); ($lev2_name eq "2nd1") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test objChild() & objValue() # $lev3_node = $lev2_node->objChild(); if (!$lev3_node) { result($testnum, 0); } $val = $lev3_node->objValue(); ($val eq "value1") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test objNext() # $next_node = $lev3_node->objNext(); if (!$lev3_node) { result($testnum, 0); } $nam = $next_node->objName(); ($nam eq "Entry2") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test getChild() # $lev2_node = $hdf->getChild("TopNode.2nd1"); $lev2_node ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test setValue() & getValue() # $hdf->setValue("Data.1", "Value1"); $str = $hdf->getValue("Data.1", "default"); ($str eq "Value1") ? result($testnum, 1) : result($testnum, 0); $testnum++; $str = $hdf->getValue("Data.2", "default"); # doesn't exist ($str eq "default") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test copy tree # $copy = ClearSilver::HDF->new(); $ret = $copy->copy("", $hdf); $ret ? result($testnum, 0) : result($testnum, 1); $testnum++; $str = $copy->getValue("Data.1", "default"); print $str ($str eq "Value1") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test setSymlink() # $ret = $copy->setSymlink( "BottomNode" ,"TopNode"); $ret ? result($testnum, 1) : result($testnum, 0); $testnum++; $tmp = $copy->getObj("BottomNode.2nd1"); $tmp ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test removeTree() # $ret = $copy->removeTree("TopNode"); $ret ? result($testnum, 1) : result($testnum, 0); $testnum++; $tmp = $copy->getObj("TopNode.2nd1"); $tmp ? result($testnum, 0) : result($testnum, 1); $testnum++; # # test sortObj() # $sort_top = $hdf->getObj("Sort.Data"); $sort_top->sortObj("sortFunc"); $child = $sort_top->objChild(); $name = $child->objName(); ($name eq "entry3") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # test CS # $cs = ClearSilver::CS->new($hdf); $cs ? result($testnum, 1) : result($testnum, 0); $testnum++; # # parseString() and render() # $ret = $cs->parseString(""); if (!$ret) { result($testnum, 0); } $ret = $cs->render(); ($ret eq "value3") ? result($testnum, 1) : result($testnum, 0); $testnum++; # # parseFile() # $ret = $cs->parseFile("test.cs"); if (!$ret) { result($testnum, 0); } $ret = $cs->render(); open(FH, "> test.out"); print FH $ret; close(FH); $ret = system("diff test.gold test.out > /dev/null"); $ret ? result($testnum, 0) : result($testnum, 1); clearsilver-0.10.5/perl/typemap0000644001211700116100000000007410261037513013367 00000000000000TYPEMAP ClearSilver::HDF T_PTROBJ ClearSilver::CS T_PTROBJ clearsilver-0.10.5/ruby/0000755001211700116100000000000010645505045012071 500000000000000clearsilver-0.10.5/ruby/Makefile0000644001211700116100000000234010344021610013433 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk all: config.save ext/hdf/hdf.so testrb config.save: install.rb $(RUBY) install.rb config -- --with-hdf-include=../../.. --with-hdf-lib=../../../libs --make-prog=$(MAKE) ext/hdf/Makefile: $(RUBY) install.rb config -- --with-hdf-include=../../.. --with-hdf-lib=../../../libs --make-prog=$(MAKE) ext/hdf/hdf.so: config.save $(RUBY) install.rb setup gold: ext/hdf/hdf.so $(RUBY) -Ilib -Iext/hdf test/hdftest.rb > hdftest.gold; @echo "Generated gold files" testrb: ext/hdf/hdf.so @echo "Running ruby test" @failed=0; \ rm -f hdftest.out; \ $(RUBY) -Ilib -Iext/hdf test/hdftest.rb > hdftest.out; \ diff --brief hdftest.out hdftest.gold > /dev/null 2>&1; \ return_code=$$?; \ if [ $$return_code -ne 0 ]; then \ diff hdftest.out hdftest.gold > hdftest.err; \ echo "Failed Ruby Test: hdftest.rb"; \ echo " See hdftest.out and hdftest.err"; \ failed=1; \ fi; \ if [ $$failed -eq 1 ]; then \ exit 1; \ fi; @echo "Passed ruby test" install: all $(RUBY) install.rb install clean: $(RM) ext/hdf/*.o ext/hdf/*.so distclean: $(RM) Makefile.depends config.save ext/hdf/hdf.so $(RM) ext/hdf/Makefile ext/hdf/mkmf.log ext/hdf/*.o clearsilver-0.10.5/ruby/ext/0000755001211700116100000000000010645505045012671 500000000000000clearsilver-0.10.5/ruby/ext/hdf/0000755001211700116100000000000010645505045013432 500000000000000clearsilver-0.10.5/ruby/ext/hdf/MANIFEST0000644001211700116100000000005010261037514014471 00000000000000MANIFEST extconf.rb neo_cs.c neo_util.c clearsilver-0.10.5/ruby/ext/hdf/extconf.rb0000644001211700116100000000047710261037514015350 00000000000000#!/usr/bin/env ruby require 'mkmf' # dir_config("hdf","../../..","../../../libs") dir_config("hdf") have_library("z", "deflate") if have_header("ClearSilver.h") && have_library("neo_utl","hdf_init") && have_library("neo_cs","cs_init") && have_library("neo_cgi","cgi_register_strfuncs") create_makefile("hdf") end clearsilver-0.10.5/ruby/ext/hdf/neo_cs.c0000644001211700116100000000501010565175553014770 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include #include "ClearSilver.h" #include "neo_ruby.h" static VALUE cCs; extern VALUE mNeotonic; extern VALUE eHdfError; VALUE r_neo_error(NEOERR *err); #define Srb_raise(val) rb_raise(eHdfError, "%s/%d %s",__FILE__,__LINE__,RSTRING(val)->ptr) static void c_free (CSPARSE *csd) { if (csd) { cs_destroy (&csd); } } static VALUE c_init (VALUE self) { return self; } VALUE c_new (VALUE class, VALUE oHdf) { CSPARSE *cs = NULL; NEOERR *err; t_hdfh *hdfh; VALUE r_cs; Data_Get_Struct(oHdf, t_hdfh, hdfh); if (hdfh == NULL) rb_raise(eHdfError, "must include an Hdf object"); err = cs_init (&cs, hdfh->hdf); if (err) Srb_raise(r_neo_error(err)); err = cgi_register_strfuncs(cs); if (err) Srb_raise(r_neo_error(err)); r_cs = Data_Wrap_Struct(class, 0, c_free, cs); rb_obj_call_init(r_cs, 0, NULL); return r_cs; } static VALUE c_parse_file (VALUE self, VALUE oPath) { CSPARSE *cs = NULL; NEOERR *err; char *path; Data_Get_Struct(self, CSPARSE, cs); path = STR2CSTR(oPath); err = cs_parse_file (cs, path); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE c_parse_str (VALUE self, VALUE oString) { CSPARSE *cs = NULL; NEOERR *err; char *s, *ms; long l; Data_Get_Struct(self, CSPARSE, cs); s = rb_str2cstr(oString, &l); /* This should be changed to use memory from the gc */ ms = strdup(s); if (ms == NULL) rb_raise(rb_eNoMemError, "out of memory"); err = cs_parse_string (cs, ms, (size_t)l); if (err) Srb_raise(r_neo_error(err)); return self; } static NEOERR *render_cb (void *ctx, char *buf) { STRING *str= (STRING *)ctx; return nerr_pass(string_append(str, buf)); } static VALUE c_render (VALUE self) { CSPARSE *cs = NULL; NEOERR *err; STRING str; VALUE rv; Data_Get_Struct(self, CSPARSE, cs); string_init(&str); err = cs_render (cs, &str, render_cb); if (err) Srb_raise(r_neo_error(err)); rv = rb_str_new2(str.buf); string_clear (&str); return rv; } void Init_cs() { cCs = rb_define_class_under(mNeotonic, "Cs", rb_cObject); rb_define_singleton_method(cCs, "new", c_new, 1); rb_define_method(cCs, "initialize", c_init, 0); rb_define_method(cCs, "parse_file", c_parse_file, 1); rb_define_method(cCs, "parse_string", c_parse_str, 1); rb_define_method(cCs, "render", c_render, 0); } clearsilver-0.10.5/ruby/ext/hdf/neo_ruby.h0000644001211700116100000000021210565175553015350 00000000000000 #ifndef __NEO_RUBY_H_ #define __NEO_RUBY_H_ typedef struct s_hdfh { HDF *hdf; struct s_hdfh *parent; VALUE top; } t_hdfh; #endif clearsilver-0.10.5/ruby/ext/hdf/neo_util.c0000644001211700116100000003020110565175603015334 00000000000000/* * Copyright 2001-2004 Brandon Long * All Rights Reserved. * * ClearSilver Templating System * * This code is made available under the terms of the ClearSilver License. * http://www.clearsilver.net/license.hdf * */ #include #include #include "ClearSilver.h" #include "neo_ruby.h" VALUE mNeotonic; static VALUE cHdf; VALUE eHdfError; static ID id_to_s; #define Srb_raise(val) rb_raise(eHdfError, "%s/%d %s",__FILE__,__LINE__,RSTRING(val)->ptr) VALUE r_neo_error (NEOERR *err) { STRING str; VALUE errstr; string_init (&str); nerr_error_string (err, &str); errstr = rb_str_new2(str.buf); /* if (nerr_match(err, NERR_PARSE)) { } else { } */ string_clear (&str); return errstr; } static void h_free2(t_hdfh *hdfh) { #ifdef DEBUG fprintf(stderr,"freeing hdf 0x%x\n",hdfh); #endif hdf_destroy(&(hdfh->hdf)); free(hdfh); } static void h_free(t_hdfh *hdfh) { #ifdef DEBUG fprintf(stderr,"freeing hdf holder 0x%x of 0x%x\n",hdfh,hdfh->parent); #endif free(hdfh); } static void h_mark(t_hdfh *hdfh) { /* Only mark the array if this is the top node, only the original node should set up the marker. */ #ifdef DEBUG fprintf(stderr,"marking 0x%x\n",hdfh); #endif if ( ! NIL_P(hdfh->top) ) rb_gc_mark(hdfh->top); else fprintf(stderr,"mark top 0x%x\n",hdfh); } static VALUE h_init (VALUE self) { return self; } VALUE h_new(VALUE class) { t_hdfh *hdfh; NEOERR *err; VALUE obj; obj=Data_Make_Struct(class,t_hdfh,0,h_free2,hdfh); err = hdf_init (&(hdfh->hdf)); if (err) Srb_raise(r_neo_error(err)); #ifdef DEBUG fprintf(stderr,"allocated 0x%x\n",(void *)hdfh); #endif hdfh->top=Qnil; rb_obj_call_init(obj, 0, NULL); return obj; } static VALUE h_get_attr (VALUE self, VALUE oName) { t_hdfh *hdfh; char *name; HDF_ATTR *attr; VALUE k,v; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); name = STR2CSTR(oName); rv = rb_hash_new(); attr = hdf_get_attr(hdfh->hdf, name); while ( attr != NULL ) { k=rb_str_new2(attr->key); v=rb_str_new2(attr->value); rb_hash_aset(rv, k, v); attr = attr->next; } return rv; } static VALUE h_set_attr(VALUE self, VALUE oName, VALUE oKey, VALUE oValue) { t_hdfh *hdfh; char *name, *key, *value; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); name = STR2CSTR(oName); key = STR2CSTR(oKey); if ( NIL_P(oValue) ) value = NULL; else value = STR2CSTR(oValue); err = hdf_set_attr(hdfh->hdf, name, key, value); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_set_value (VALUE self, VALUE oName, VALUE oValue) { t_hdfh *hdfh; char *name, *value; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); if ( TYPE(oName) == T_STRING ) name=STR2CSTR(oName); else name=STR2CSTR(rb_funcall(oName,id_to_s,0)); if ( TYPE(oValue) == T_STRING ) value=STR2CSTR(oValue); else value=STR2CSTR(rb_funcall(oValue,id_to_s,0)); err = hdf_set_value (hdfh->hdf, name, value); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_get_int_value (VALUE self, VALUE oName, VALUE oDefault) { t_hdfh *hdfh; char *name; int r, d = 0; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); name=STR2CSTR(oName); d=NUM2INT(oDefault); r = hdf_get_int_value (hdfh->hdf, name, d); rv = INT2NUM(r); return rv; } static VALUE h_get_value (VALUE self, VALUE oName, VALUE oDefault) { t_hdfh *hdfh; char *name; char *r, *d = NULL; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); name=STR2CSTR(oName); d=STR2CSTR(oDefault); r = hdf_get_value (hdfh->hdf, name, d); rv = rb_str_new2(r); return rv; } static VALUE h_get_child (VALUE self, VALUE oName) { t_hdfh *hdfh,*hdfh_new; HDF *r; VALUE rv; char *name; Data_Get_Struct(self, t_hdfh, hdfh); name=STR2CSTR(oName); r = hdf_get_child (hdfh->hdf, name); if (r == NULL) { return Qnil; } rv=Data_Make_Struct(cHdf,t_hdfh,h_mark,h_free,hdfh_new); hdfh_new->top=self; hdfh_new->hdf=r; hdfh_new->parent=hdfh; return rv; } static VALUE h_get_obj (VALUE self, VALUE oName) { t_hdfh *hdfh,*hdfh_new; HDF *r; VALUE rv; char *name; Data_Get_Struct(self, t_hdfh, hdfh); name=STR2CSTR(oName); r = hdf_get_obj (hdfh->hdf, name); if (r == NULL) { return Qnil; } rv=Data_Make_Struct(cHdf,t_hdfh,h_mark,h_free,hdfh_new); hdfh_new->top=self; hdfh_new->hdf=r; hdfh_new->parent=hdfh; return rv; } static VALUE h_get_node (VALUE self, VALUE oName) { t_hdfh *hdfh,*hdfh_new; HDF *r; VALUE rv; char *name; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); name=STR2CSTR(oName); err = hdf_get_node (hdfh->hdf, name, &r); if (err) Srb_raise(r_neo_error(err)); rv=Data_Make_Struct(cHdf,t_hdfh,h_mark,h_free,hdfh_new); hdfh_new->top=self; hdfh_new->hdf=r; hdfh_new->parent=hdfh; return rv; } static VALUE h_obj_child (VALUE self) { t_hdfh *hdfh,*hdfh_new; HDF *r = NULL; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); r = hdf_obj_child (hdfh->hdf); if (r == NULL) { return Qnil; } rv=Data_Make_Struct(cHdf,t_hdfh,h_mark,h_free,hdfh_new); hdfh_new->top=self; hdfh_new->hdf=r; hdfh_new->parent=hdfh; return rv; } static VALUE h_obj_next (VALUE self) { t_hdfh *hdfh,*hdfh_new; HDF *r = NULL; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); r = hdf_obj_next (hdfh->hdf); if (r == NULL) { return Qnil; } rv=Data_Make_Struct(cHdf,t_hdfh,h_mark,h_free,hdfh_new); hdfh_new->top=self; hdfh_new->hdf=r; hdfh_new->parent=hdfh; return rv; } static VALUE h_obj_top (VALUE self) { t_hdfh *hdfh,*hdfh_new; HDF *r = NULL; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); r = hdf_obj_top (hdfh->hdf); if (r == NULL) { return Qnil; } rv=Data_Make_Struct(cHdf,t_hdfh,h_mark,h_free,hdfh_new); hdfh_new->top=self; hdfh_new->hdf=r; hdfh_new->parent=hdfh; return rv; } static VALUE h_obj_name (VALUE self) { t_hdfh *hdfh; VALUE rv; char *r; Data_Get_Struct(self, t_hdfh, hdfh); r = hdf_obj_name (hdfh->hdf); if (r == NULL) { return Qnil; } rv = rb_str_new2(r); return rv; } static VALUE h_obj_attr (VALUE self) { t_hdfh *hdfh; HDF_ATTR *attr; VALUE k,v; VALUE rv; Data_Get_Struct(self, t_hdfh, hdfh); rv = rb_hash_new(); attr = hdf_obj_attr(hdfh->hdf); while ( attr != NULL ) { k=rb_str_new2(attr->key); v=rb_str_new2(attr->value); rb_hash_aset(rv, k, v); attr = attr->next; } return rv; } static VALUE h_obj_value (VALUE self) { t_hdfh *hdfh; VALUE rv; char *r; Data_Get_Struct(self, t_hdfh, hdfh); r = hdf_obj_value (hdfh->hdf); if (r == NULL) { return Qnil; } rv = rb_str_new2(r); return rv; } static VALUE h_read_file (VALUE self, VALUE oPath) { t_hdfh *hdfh; char *path; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); path=STR2CSTR(oPath); err = hdf_read_file (hdfh->hdf, path); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_write_file (VALUE self, VALUE oPath) { t_hdfh *hdfh; char *path; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); path=STR2CSTR(oPath); err = hdf_write_file (hdfh->hdf, path); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_write_file_atomic (VALUE self, VALUE oPath) { t_hdfh *hdfh; char *path; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); path=STR2CSTR(oPath); err = hdf_write_file_atomic (hdfh->hdf, path); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_remove_tree (VALUE self, VALUE oName) { t_hdfh *hdfh; char *name; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); name = STR2CSTR(oName); err = hdf_remove_tree (hdfh->hdf, name); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_dump (VALUE self) { t_hdfh *hdfh; VALUE rv; NEOERR *err; STRING str; string_init (&str); Data_Get_Struct(self, t_hdfh, hdfh); err = hdf_dump_str (hdfh->hdf, NULL, 0, &str); if (err) Srb_raise(r_neo_error(err)); if (str.len==0) return Qnil; rv = rb_str_new2(str.buf); string_clear (&str); return rv; } static VALUE h_write_string (VALUE self) { t_hdfh *hdfh; VALUE rv; NEOERR *err; char *s = NULL; Data_Get_Struct(self, t_hdfh, hdfh); err = hdf_write_string (hdfh->hdf, &s); if (err) Srb_raise(r_neo_error(err)); rv = rb_str_new2(s); if (s) free(s); return rv; } static VALUE h_read_string (VALUE self, VALUE oString, VALUE oIgnore) { t_hdfh *hdfh; NEOERR *err; char *s = NULL; int ignore = 0; Data_Get_Struct(self, t_hdfh, hdfh); s = STR2CSTR(oString); ignore = NUM2INT(oIgnore); err = hdf_read_string_ignore (hdfh->hdf, s, ignore); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_copy (VALUE self, VALUE oName, VALUE oHdfSrc) { t_hdfh *hdfh, *hdfh_src; char *name; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); Data_Get_Struct(oHdfSrc, t_hdfh, hdfh_src); name = STR2CSTR(oName); if (hdfh_src == NULL) rb_raise(eHdfError, "second argument must be an Hdf object"); err = hdf_copy (hdfh->hdf, name, hdfh_src->hdf); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_set_symlink (VALUE self, VALUE oSrc, VALUE oDest) { t_hdfh *hdfh; char *src; char *dest; NEOERR *err; Data_Get_Struct(self, t_hdfh, hdfh); src = STR2CSTR(oSrc); dest = STR2CSTR(oDest); err = hdf_set_symlink (hdfh->hdf, src, dest); if (err) Srb_raise(r_neo_error(err)); return self; } static VALUE h_escape (VALUE self, VALUE oString, VALUE oEsc_char, VALUE oEsc) { VALUE rv; char *s; char *escape; char *esc_char; long buflen; char *ret = NULL; NEOERR *err; s = rb_str2cstr(oString,&buflen); esc_char = STR2CSTR(oEsc_char); escape = STR2CSTR(oEsc); err = neos_escape((UINT8*)s, buflen, esc_char[0], escape, &ret); if (err) Srb_raise(r_neo_error(err)); rv = rb_str_new2(ret); free(ret); return rv; } static VALUE h_unescape (VALUE self, VALUE oString, VALUE oEsc_char) { VALUE rv; char *s; char *copy; char *esc_char; long buflen; s = rb_str2cstr(oString,&buflen); esc_char = STR2CSTR(oEsc_char); /* This should be changed to use memory from the gc */ copy = strdup(s); if (copy == NULL) rb_raise(rb_eNoMemError, "out of memory"); neos_unescape((UINT8*)copy, buflen, esc_char[0]); rv = rb_str_new2(copy); free(copy); return rv; } void Init_cs(); void Init_hdf() { id_to_s=rb_intern("to_s"); mNeotonic = rb_define_module("Neo"); cHdf = rb_define_class_under(mNeotonic, "Hdf", rb_cObject); rb_define_singleton_method(cHdf, "new", h_new, 0); rb_define_method(cHdf, "initialize", h_init, 0); rb_define_method(cHdf, "get_attr", h_get_attr, 1); rb_define_method(cHdf, "set_attr", h_set_attr, 3); rb_define_method(cHdf, "set_value", h_set_value, 2); rb_define_method(cHdf, "put", h_set_value, 2); rb_define_method(cHdf, "get_int_value", h_get_int_value, 2); rb_define_method(cHdf, "get_value", h_get_value, 2); rb_define_method(cHdf, "get_child", h_get_child, 1); rb_define_method(cHdf, "get_obj", h_get_obj, 1); rb_define_method(cHdf, "get_node", h_get_node, 1); rb_define_method(cHdf, "obj_child", h_obj_child, 0); rb_define_method(cHdf, "obj_next", h_obj_next, 0); rb_define_method(cHdf, "obj_top", h_obj_top, 0); rb_define_method(cHdf, "obj_name", h_obj_name, 0); rb_define_method(cHdf, "obj_attr", h_obj_attr, 0); rb_define_method(cHdf, "obj_value", h_obj_value, 0); rb_define_method(cHdf, "read_file", h_read_file, 1); rb_define_method(cHdf, "write_file", h_write_file, 1); rb_define_method(cHdf, "write_file_atomic", h_write_file_atomic, 1); rb_define_method(cHdf, "remove_tree", h_remove_tree, 1); rb_define_method(cHdf, "dump", h_dump, 0); rb_define_method(cHdf, "write_string", h_write_string, 0); rb_define_method(cHdf, "read_string", h_read_string, 2); rb_define_method(cHdf, "copy", h_copy, 2); rb_define_method(cHdf, "set_symlink", h_set_symlink, 2); rb_define_singleton_method(cHdf, "escape", h_escape, 3); rb_define_singleton_method(cHdf, "unescape", h_unescape, 3); eHdfError = rb_define_class_under(mNeotonic, "HdfError", #if RUBY_VERSION_MINOR >= 6 rb_eStandardError); #else rb_eException); #endif Init_cs(); } clearsilver-0.10.5/ruby/hdftest.gold0000644001211700116100000000062210261037515014315 000000000000001 = farming 2 = sewing 3 = bowling party.1 [Drool="True"] = baloons party.2 [Pink] = noise makers party.3 << EOM telling long stories EOM arf.1 = farming arf.2 = sewing arf.3 = bowling arf.party.1 [Drool="True"] = baloons arf.party.2 [Pink] = noise makers arf.party.3 << EOM telling long stories EOM party.2 attr (Pink=1) This is a funny test. farming. baloons noise makers telling long stories clearsilver-0.10.5/ruby/install.rb0000644001211700116100000005214010261037515014002 00000000000000# # This file is automatically generated. DO NOT MODIFY! # # install.rb # # Copyright (c) 2000-2002 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU Lesser General Public License version 2. # ### begin compat.rb unless Enumerable.instance_methods.include? 'inject' then module Enumerable def inject( result ) each do |i| result = yield(result, i) end result end end end def File.read_all( fname ) File.open(fname, 'rb') {|f| return f.read } end def File.write( fname, str ) File.open(fname, 'wb') {|f| f.write str } end ### end compat.rb ### begin config.rb if i = ARGV.index(/\A--rbconfig=/) then file = $' ARGV.delete_at(i) require file else require 'rbconfig' end class ConfigTable c = ::Config::CONFIG rubypath = c['bindir'] + '/' + c['ruby_install_name'] major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) re = Regexp.new('\A' + Regexp.quote(c['prefix'])) subprefix = lambda {|path| re === path and path.sub(re, '$prefix') } if c['rubylibdir'] then # 1.6.3 < V stdruby = subprefix.call(c['rubylibdir']) siteruby = subprefix.call(c['sitedir']) versite = subprefix.call(c['sitelibdir']) sodir = subprefix.call(c['sitearchdir']) elsif newpath_p then # 1.4.4 <= V <= 1.6.3 stdruby = "$prefix/lib/ruby/#{version}" siteruby = subprefix.call(c['sitedir']) versite = siteruby + '/' + version sodir = "$site-ruby/#{c['arch']}" else # V < 1.4.4 stdruby = "$prefix/lib/ruby/#{version}" siteruby = "$prefix/lib/ruby/#{version}/site_ruby" versite = siteruby sodir = "$site-ruby/#{c['arch']}" end DESCRIPTER = [ [ 'prefix', [ c['prefix'], 'path', 'path prefix of target environment' ] ], [ 'std-ruby', [ stdruby, 'path', 'the directory for standard ruby libraries' ] ], [ 'site-ruby-common', [ siteruby, 'path', 'the directory for version-independent non-standard ruby libraries' ] ], [ 'site-ruby', [ versite, 'path', 'the directory for non-standard ruby libraries' ] ], [ 'bin-dir', [ '$prefix/bin', 'path', 'the directory for commands' ] ], [ 'rb-dir', [ '$site-ruby', 'path', 'the directory for ruby scripts' ] ], [ 'so-dir', [ sodir, 'path', 'the directory for ruby extentions' ] ], [ 'data-dir', [ '$prefix/share', 'path', 'the directory for shared data' ] ], [ 'ruby-path', [ rubypath, 'path', 'path to set to #! line' ] ], [ 'ruby-prog', [ rubypath, 'name', 'the ruby program using for installation' ] ], [ 'make-prog', [ 'make', 'name', 'the make program to compile ruby extentions' ] ], [ 'without-ext', [ 'no', 'yes/no', 'does not compile/install ruby extentions' ] ] ] SAVE_FILE = 'config.save' def ConfigTable.each_name( &block ) keys().each( &block ) end def ConfigTable.keys DESCRIPTER.collect {|k,*dummy| k } end def ConfigTable.each_definition( &block ) DESCRIPTER.each( &block ) end def ConfigTable.get_entry( name ) name, ent = DESCRIPTER.assoc(name) ent end def ConfigTable.get_entry!( name ) get_entry(name) or raise ArgumentError, "no such config: #{name}" end def ConfigTable.add_entry( name, vals ) ConfigTable::DESCRIPTER.push [name,vals] end def ConfigTable.remove_entry( name ) get_entry name or raise ArgumentError, "no such config: #{name}" DESCRIPTER.delete_if {|n,arr| n == name } end def ConfigTable.config_key?( name ) get_entry(name) ? true : false end def ConfigTable.bool_config?( name ) ent = get_entry(name) or return false ent[1] == 'yes/no' end def ConfigTable.value_config?( name ) ent = get_entry(name) or return false ent[1] != 'yes/no' end def ConfigTable.path_config?( name ) ent = get_entry(name) or return false ent[1] == 'path' end class << self alias newobj new def new c = newobj() c.__send__ :init c end def load c = newobj() File.file? SAVE_FILE or raise InstallError, "#{File.basename $0} config first" File.foreach( SAVE_FILE ) do |line| k, v = line.split( '=', 2 ) c.instance_eval { @table[k] = v.strip } end c end end def initialize @table = {} end def init DESCRIPTER.each do |k, (default, vname, desc, default2)| @table[k] = default end end private :init def save File.open( SAVE_FILE, 'w' ) {|f| @table.each do |k, v| f.printf "%s=%s\n", k, v if v end } end def []=( k, v ) ConfigTable.config_key? k or raise InstallError, "unknown config option #{k}" if ConfigTable.path_config? k then @table[k] = (v[0,1] != '$') ? File.expand_path(v) : v else @table[k] = v end end def []( key ) @table[key] or return nil @table[key].gsub( %r<\$([^/]+)> ) { self[$1] } end def set_raw( key, val ) @table[key] = val end def get_raw( key ) @table[key] end end class MetaConfigEnvironment def self.eval_file( file ) return unless File.file? file new.instance_eval File.read_all(file), file, 1 end private def config_names ConfigTable.keys end def config?( name ) ConfigTable.config_key? name end def bool_config?( name ) ConfigTable.bool_config? name end def value_config?( name ) ConfigTable.value_config? name end def path_config?( name ) ConfigTable.path_config? name end def add_config( name, argname, default, desc ) ConfigTable.add_entry name,[default,argname,desc] end def add_path_config( name, default, desc ) add_config name, 'path', default, desc end def add_bool_config( name, default, desc ) add_config name, 'yes/no', default ? 'yes' : 'no', desc end def set_config_default( name, default ) if bool_config? name then ConfigTable.get_entry!(name)[0] = default ? 'yes' : 'no' else ConfigTable.get_entry!(name)[0] = default end end def remove_config( name ) ent = ConfigTable.get_entry(name) ConfigTable.remove_entry name ent end end ### end config.rb ### begin fileop.rb module FileOperations def mkdir_p( dname, prefix = nil ) dname = prefix + dname if prefix $stderr.puts "mkdir -p #{dname}" if verbose? return if no_harm? # does not check '/'... it's too abnormal case dirs = dname.split(%r_(?=/)_) if /\A[a-z]:\z/i === dirs[0] then disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless dir? path end end def rm_f( fname ) $stderr.puts "rm -f #{fname}" if verbose? return if no_harm? if File.exist? fname or File.symlink? fname then File.chmod 0777, fname File.unlink fname end end def rm_rf( dn ) $stderr.puts "rm -rf #{dn}" if verbose? return if no_harm? Dir.chdir dn Dir.foreach('.') do |fn| next if fn == '.' next if fn == '..' if dir? fn then verbose_off { rm_rf fn } else verbose_off { rm_f fn } end end Dir.chdir '..' Dir.rmdir dn end def mv( src, dest ) rm_f dest begin File.link src, dest rescue File.write dest, File.read_all(src) File.chmod File.stat(src).mode, dest end rm_f src end def install( from, dest, mode, prefix = nil ) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix + dest if prefix if dir? realdest then realdest += '/' + File.basename(from) end str = File.read_all(from) if diff? str, realdest then verbose_off { rm_f realdest if File.exist? realdest } File.write realdest, str File.chmod mode, realdest File.open( objdir + '/InstalledFiles', 'a' ) {|f| f.puts realdest } end end def diff?( orig, targ ) return true unless File.exist? targ orig != File.read_all(targ) end def command( str ) $stderr.puts str if verbose? system str or raise RuntimeError, "'system #{str}' failed" end def ruby( str ) command config('ruby-prog') + ' ' + str end def dir?( dname ) # for corrupted windows stat() File.directory?( (dname[-1,1] == '/') ? dname : dname + '/' ) end def all_files( dname ) Dir.open( dname ) {|d| return d.find_all {|n| File.file? "#{dname}/#{n}" } } end def all_dirs( dname ) Dir.open( dname ) {|d| return d.find_all {|n| dir? "#{dname}/#{n}" } - %w(. ..) } end end ### end fileop.rb ### begin base.rb class InstallError < StandardError; end class Installer Version = '3.1.2' Copyright = 'Copyright (c) 2000-2002 Minero Aoki' @toplevel = nil def self.declear_toplevel_installer( inst ) @toplevel and raise ArgumentError, 'more than one toplevel installer decleared' @toplevel = inst end def self.toplevel_installer @toplevel end FILETYPES = %w( bin lib ext data ) include FileOperations def initialize( config, opt, srcroot, objroot ) @config = config @options = opt @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{type} #{__id__}>" end # # configs/options # def get_config( key ) @config[key] end alias config get_config def set_config( key, val ) @config[key] = val end def no_harm? @options['no-harm'] end def verbose? @options['verbose'] end def verbose_off save, @options['verbose'] = @options['verbose'], false yield @options['verbose'] = save end # # srcdir/objdir # attr_reader :srcdir alias srcdir_root srcdir alias package_root srcdir def curr_srcdir "#{@srcdir}/#{@currdir}" end attr_reader :objdir alias objdir_root objdir def curr_objdir "#{@objdir}/#{@currdir}" end def srcfile( path ) curr_srcdir + '/' + path end def srcexist?( path ) File.exist? srcfile(path) end def srcdirectory?( path ) dir? srcfile(path) end def srcfile?( path ) File.file? srcfile(path) end def srcentries( path = '.' ) Dir.open( curr_srcdir + '/' + path ) {|d| return d.to_a - %w(. ..) - hookfilenames } end def srcfiles( path = '.' ) srcentries(path).find_all {|fname| File.file? File.join(curr_srcdir, path, fname) } end def srcdirectories( path = '.' ) srcentries(path).find_all {|fname| dir? File.join(curr_srcdir, path, fname) } end def dive_into( rel ) return unless dir? "#{@srcdir}/#{rel}" dir = File.basename(rel) Dir.mkdir dir unless dir? dir save = Dir.pwd Dir.chdir dir $stderr.puts '---> ' + rel if verbose? @currdir = rel yield Dir.chdir save $stderr.puts '<--- ' + rel if verbose? @currdir = File.dirname(rel) end # # config # def exec_config exec_task_traverse 'config' end def config_dir_bin( rel ) end def config_dir_lib( rel ) end def config_dir_ext( rel ) extconf if extdir? curr_srcdir end def extconf opt = @options['config-opt'].join(' ') command "#{config('ruby-prog')} #{curr_srcdir}/extconf.rb #{opt}" end def config_dir_data( rel ) end # # setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin( relpath ) all_files( curr_srcdir ).each do |fname| add_rubypath "#{curr_srcdir}/#{fname}" end end SHEBANG_RE = /\A\#!\s*\S*ruby\S*/ def add_rubypath( path ) $stderr.puts %Q if verbose? return if no_harm? tmpfile = File.basename(path) + '.tmp' begin File.open( path ) {|r| File.open( tmpfile, 'w' ) {|w| first = r.gets return unless SHEBANG_RE === first # reject '/usr/bin/env ruby' w.print first.sub( SHEBANG_RE, '#!' + config('ruby-path') ) w.write r.read } } mv tmpfile, File.basename(path) ensure rm_f tmpfile if File.exist? tmpfile end end def setup_dir_lib( relpath ) end def setup_dir_ext( relpath ) if extdir? curr_srcdir then make end end def make command config('make-prog') end def setup_dir_data( relpath ) end # # install # def exec_install exec_task_traverse 'install' end def install_dir_bin( rel ) install_files targfiles, config('bin-dir') + '/' + rel, 0755 end def install_dir_lib( rel ) install_files targfiles, config('rb-dir') + '/' + rel, 0644 end def install_dir_ext( rel ) if extdir? curr_srcdir then install_dir_ext_main File.dirname(rel) end end def install_dir_ext_main( rel ) install_files allext('.'), config('so-dir') + '/' + rel, 0555 end def install_dir_data( rel ) install_files targfiles, config('data-dir') + '/' + rel, 0644 end def install_files( list, dest, mode ) mkdir_p dest, @options['install-prefix'] list.each do |fname| install fname, dest, mode, @options['install-prefix'] end end def targfiles (targfilenames() - hookfilenames()).collect {|fname| File.exist?(fname) ? fname : File.join(curr_srcdir(), fname) } end def targfilenames [ curr_srcdir(), '.' ].inject([]) {|ret, dir| ret | all_files(dir) } end def hookfilenames %w( pre-%s post-%s pre-%s.rb post-%s.rb ).collect {|fmt| %w( config setup install clean ).collect {|t| sprintf fmt, t } }.flatten end def allext( dir ) _allext(dir) or raise InstallError, "no extention exists: Have you done 'ruby #{$0} setup' ?" end DLEXT = /\.#{ ::Config::CONFIG['DLEXT'] }\z/ def _allext( dir ) Dir.open( dir ) {|d| return d.find_all {|fname| DLEXT === fname } } end # # clean # def exec_clean exec_task_traverse 'clean' rm_f 'config.save' rm_f 'InstalledFiles' end def clean_dir_bin( rel ) end def clean_dir_lib( rel ) end def clean_dir_ext( rel ) clean end def clean command config('make-prog') + ' clean' if File.file? 'Makefile' end def clean_dir_data( rel ) end # # lib # def exec_task_traverse( task ) run_hook 'pre-' + task FILETYPES.each do |type| if config('without-ext') == 'yes' and type == 'ext' then $stderr.puts 'skipping ext/* by user option' if verbose? next end traverse task, type, task + '_dir_' + type end run_hook 'post-' + task end def traverse( task, rel, mid ) dive_into( rel ) { run_hook 'pre-' + task __send__ mid, rel.sub( %r_\A.*?(?:/|\z)_, '' ) all_dirs( curr_srcdir ).each do |d| traverse task, rel + '/' + d, mid end run_hook 'post-' + task } end def run_hook( name ) try_run_hook curr_srcdir + '/' + name or try_run_hook curr_srcdir + '/' + name + '.rb' end def try_run_hook( fname ) return false unless File.file? fname env = self.dup begin env.instance_eval File.read_all(fname), fname, 1 rescue raise InstallError, "hook #{fname} failed:\n" + $!.message end true end def extdir?( dir ) File.exist? dir + '/MANIFEST' end end ### end base.rb ### begin toplevel.rb class ToplevelInstaller < Installer TASKS = [ [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles extention or else' ], [ 'install', 'installs files' ], [ 'clean', "does `make clean' for each extention" ] ] def initialize( root ) super nil, {'verbose' => true}, root, '.' Installer.declear_toplevel_installer self end def execute run_metaconfigs case task = parsearg_global() when 'config' @config = ConfigTable.new else @config = ConfigTable.load end parsearg_TASK task exectask task end def run_metaconfigs MetaConfigEnvironment.eval_file "#{srcdir_root}/#{metaconfig}" end def metaconfig 'metaconfig' end def exectask( task ) if task == 'show' then exec_show else try task end end def try( task ) $stderr.printf "#{File.basename $0}: entering %s phase...\n", task if verbose? begin __send__ 'exec_' + task rescue $stderr.printf "%s failed\n", task raise end $stderr.printf "#{File.basename $0}: %s done.\n", task if verbose? end # # processing arguments # def parsearg_global task_re = /\A(?:#{TASKS.collect {|i| i[0] }.join '|'})\z/ while arg = ARGV.shift do case arg when /\A\w+\z/ task_re === arg or raise InstallError, "wrong task: #{arg}" return arg when '-q', '--quiet' @options['verbose'] = false when '--verbose' @options['verbose'] = true when '-h', '--help' print_usage $stdout exit 0 when '-v', '--version' puts "#{File.basename $0} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else raise InstallError, "unknown global option '#{arg}'" end end raise InstallError, 'no task or global option given' end def parsearg_TASK( task ) mid = "parsearg_#{task}" if respond_to? mid, true then __send__ mid else ARGV.empty? or raise InstallError, "#{task}: unknown options: #{ARGV.join ' '}" end end def parsearg_config re = /\A--(#{ConfigTable.keys.join '|'})(?:=(.*))?\z/ @options['config-opt'] = [] while i = ARGV.shift do if /\A--?\z/ === i then @options['config-opt'] = ARGV.dup break end m = re.match(i) or raise InstallError, "config: unknown option #{i}" name, value = m.to_a[1,2] if value then if ConfigTable.bool_config?(name) then /\A(y(es)?|n(o)?|t(rue)?|f(alse))\z/i === value or raise InstallError, "config: --#{name} allows only yes/no for argument" value = (/\Ay(es)?|\At(rue)/i === value) ? 'yes' : 'no' end else ConfigTable.bool_config?(name) or raise InstallError, "config: --#{name} requires argument" value = 'yes' end @config[name] = value end end def parsearg_install @options['no-harm'] = false @options['install-prefix'] = '' while a = ARGV.shift do case a when /\A--no-harm\z/ @options['no-harm'] = true when /\A--prefix=(.*)\z/ path = $1 path = File.expand_path(path) unless path[0,1] == '/' @options['install-prefix'] = path else raise InstallError, "install: unknown option #{a}" end end end def print_usage( out ) out.puts out.puts 'Usage:' out.puts " ruby #{File.basename $0} " out.puts " ruby #{File.basename $0} [] []" fmt = " %-20s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, '-h,--help', 'print this message' out.printf fmt, '-v,--version', 'print version and quit' out.printf fmt, '--copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf " %-10s %s\n", name, desc end out.puts out.puts 'Options for config:' ConfigTable.each_definition do |name, (default, arg, desc, default2)| out.printf " %-20s %s [%s]\n", '--'+ name + (ConfigTable.bool_config?(name) ? '' : '='+arg), desc, default2 || default end out.printf " %-20s %s [%s]\n", '--rbconfig=path', 'your rbconfig.rb to load', "running ruby's" out.puts out.puts 'Options for install:' out.printf " %-20s %s [%s]\n", '--no-harm', 'only display what to do if given', 'off' out.puts end # # config # def exec_config super @config.save end # # show # def exec_show ConfigTable.each_name do |k| v = @config.get_raw(k) if not v or v.empty? then v = '(not specified)' end printf "%-10s %s\n", k, v end end end ### end toplevel.rb if $0 == __FILE__ then begin installer = ToplevelInstaller.new( File.dirname($0) ) installer.execute rescue raise if $DEBUG $stderr.puts $!.message $stderr.puts "try 'ruby #{$0} --help' for usage" exit 1 end end clearsilver-0.10.5/ruby/lib/0000755001211700116100000000000010645505045012637 500000000000000clearsilver-0.10.5/ruby/lib/neo.rb0000644001211700116100000000114010261037515013655 00000000000000require 'hdf' module Clearsilver class Hdf < Neo::Hdf def initialize super @level=0 @cpos="" @position=[] end attr_reader :position, :cpos def push name @position.push(@cpos) @cpos+=name+"." if block_given? yield @cpos=@position.pop end end def pop @cpos=@position.pop end def put name, value value = value.to_s unless value.is_a?(String) self.set_value(@cpos+(name.to_s),value) end def get name self.get_value(@cpos+name) end end class Cs < Neo::Cs end end clearsilver-0.10.5/ruby/test/0000755001211700116100000000000010645505045013050 500000000000000clearsilver-0.10.5/ruby/test/hdftest.rb0000644001211700116100000000115010261037515014747 00000000000000#!/usr/bin/env ruby require 'neo' h=Neo::Hdf.new h.set_value "1","farming" h.set_value "2","sewing" h.set_value "3","bowling" h.set_value "party.1","baloons" h.set_value "party.2","noise makers" h.set_value "party.3","telling long\nstories" h.set_attr "party.1", "Drool", "True" h.set_attr "party.2", "Pink", "1" print h.dump q=Neo::Hdf.new q.copy "arf",h print q.dump h.get_attr("party.2").each_pair do |k,v| print "party.2 attr (#{k}=#{v})\n" end s="This is a funny test. . " c = Neo::Cs.new q c.parse_string(s) print c.render clearsilver-0.10.5/dso/0000755001211700116100000000000010645505045011675 500000000000000clearsilver-0.10.5/dso/Makefile0000644001211700116100000000134610455366411013262 00000000000000 ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk NEO_SO = libneo.so NEO_STATIC_LIBS = LIBS += $(DLIBS) $(DB2_LIB) TARGETS = $(NEO_SO) dsotest all: $(TARGETS) $(NEO_SO): $(NEO_STATIC_LIBS) $(DEP_LIBS) Makefile /usr/bin/ld -rpath ../libs -shared -o libneo.so -whole-archive ../libs/libneo_cgi.a ../libs/libneo_cs.a ../libs/libneo_utl.a -no-whole-archive $(LDFLAGS) $(LIBS) # $(LDSHARED) -o $@ $(LDFLAGS) -Wl,-whole-archive $(DLIBS) install: all $(NEOTONIC_ROOT)/mkinstalldirs $(DESTDIR)$(PYTHON_SITE) $(INSTALL) $(TARGETS) $(DESTDIR)$(PYTHON_SITE) dsotest: dsotest.c $(NEO_SO) gcc -o dsotest dsotest.c -lneo -L. -I.. clean: $(RM) *.o distclean: $(RM) Makefile.depends $(TARGETS) *.o clearsilver-0.10.5/dso/README0000644001211700116100000000061610261037511012470 00000000000000 08-18-2003 blong This directory builds a "dynamic shared object" or dso. In theory, you could use this for various things, but in reality this is for the Mono/CSharp module, which requires a shared library loadable by the C# run time. Building this dso is very system specific, and this is currently very Linux specific at the moment. Patches to build this on other platforms are appreciated. clearsilver-0.10.5/dso/dsotest.c0000644001211700116100000000031610261037511013436 00000000000000 #include int main() { HDF *hdf; NEOERR *err; err = hdf_init(&hdf); if (err) { printf("error: %s\n", err->desc); return 1; } printf("success: 0x%X\n", hdf); } clearsilver-0.10.5/csharp/0000755001211700116100000000000010645505045012370 500000000000000clearsilver-0.10.5/csharp/CS.cs0000644001211700116100000000757610645503705013164 00000000000000 using System; using System.Runtime.InteropServices; namespace Clearsilver { // opaque types public unsafe struct HDF {}; public unsafe struct NEOERR {}; public unsafe class Hdf { [DllImport("libneo", EntryPoint="hdf_init")] private static extern unsafe NEOERR* hdf_init(HDF **foo); // NEOERR* hdf_set_value (HDF *hdf, char *name, char *value) [DllImport("libneo")] private static unsafe extern NEOERR* hdf_set_value(HDF *hdf, [MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string value); // char* hdf_get_value (HDF *hdf, char *name, char *defval) [DllImport("libneo")] [return: MarshalAs(UnmanagedType.LPStr)] private static unsafe extern string hdf_get_value(HDF *hdf, [MarshalAs(UnmanagedType.LPStr)] string name, [MarshalAs(UnmanagedType.LPStr)] string defval); // NEOERR* hdf_dump (HDF *hdf, char *prefix); [DllImport("libneo", EntryPoint="hdf_dump")] private static extern void hdf_dump( HDF *hdf, [MarshalAs(UnmanagedType.LPStr)] string prefix); // HDF* hdf_get_obj (HDF *hdf, char *name) [DllImport("libneo", EntryPoint="hdf_get_obj")] private static extern HDF* hdf_get_obj( HDF *hdf, [MarshalAs(UnmanagedType.LPStr)] string name); // ----------------------------------------------------------- public HDF *hdf_root; public Hdf() { fixed (HDF **hdf_ptr = &hdf_root) { hdf_init(hdf_ptr); } // Console.WriteLine((int)hdf_root); } public void setValue(string name,string value) { hdf_set_value(hdf_root,name,value); } public string getValue(string name,string defvalue) { return hdf_get_value(hdf_root,name,defvalue); } public void test() { hdf_set_value(hdf_root,"b","1"); // hdf_read_file(hdf_root,"test.hdf"); // Console.WriteLine("b ", hdf_get_value(hdf_root,"b","5")); hdf_dump(hdf_root,null); // HDF *n = hdf_get_obj(hdf_root,"b"); // Console.WriteLine("object name {0}", // Marshal.PtrToStringAnsi((IntPtr)n->name)); } }; unsafe struct CSPARSE {}; public class CSTContext { unsafe CSPARSE *csp; unsafe public CSTContext(Hdf hdf) { fixed (CSPARSE **csp_ptr = &csp) { cs_init(csp_ptr, hdf.hdf_root); } } [DllImport("libneo")] extern static unsafe NEOERR *cs_init (CSPARSE **parse, HDF *hdf); public unsafe void parseFile(string filename) { cs_parse_file(csp,filename); } [DllImport("libneo")] extern static unsafe NEOERR *cs_parse_file (CSPARSE *parse, [MarshalAs(UnmanagedType.LPStr)] string path); // [DllImport("libneo")] // extern static unsafe NEOERR *cs_parse_string (CSPARSE *parse, // char *buf, // size_t blen); // NEOERR *cs_render (CSPARSE *parse, void *ctx, CSOUTFUNC cb); // typedef NEOERR* (*CSOUTFUNC)(void *ctx, char *more_str_bytes); [DllImport("libneo")] extern static unsafe NEOERR *cs_render (CSPARSE *parse, void *ctx, [MarshalAs(UnmanagedType.FunctionPtr)] CSOUTFUNC cb); private unsafe delegate NEOERR* CSOUTFUNC(void* ctx, sbyte* more_bytes); private class OutputBuilder { private string output = ""; public unsafe NEOERR* handleOutput(void* ctx, sbyte* more_bytes) { // add the more_bytes to the current string buffer output += new String(more_bytes); // Console.WriteLine("handleOutput called"); return null; } public string result() { return output; } } public unsafe string render() { OutputBuilder ob = new OutputBuilder(); cs_render(csp,null,new CSOUTFUNC(ob.handleOutput)); return ob.result(); } [DllImport("libneo")] extern static unsafe void cs_destroy (CSPARSE **parse); }; } // namespace Clearsilver clearsilver-0.10.5/csharp/Makefile0000644001211700116100000000255510645501565013762 00000000000000 # default values.... CSHARP_CC=$(CSHARP_PATH)/bin/mcs MONO_JIT=$(CSHARP_PATH)/bin/mono # common build environment ifeq ($(NEOTONIC_ROOT),) NEOTONIC_ROOT = .. endif include $(NEOTONIC_ROOT)/rules.mk # our targets TARGETS = clearsilver.dll cstest.exe csperftest.exe testcs all: $(TARGETS) clearsilver.dll: CS.cs $(CSHARP_CC) -target:library -unsafe CS.cs -out:clearsilver.dll cstest.exe: clearsilver.dll ../dso/libneo.so cstest.cs $(CSHARP_CC) -r:clearsilver.dll -unsafe cstest.cs csperftest.exe: clearsilver.dll ../dso/libneo.so csperftest.cs $(CSHARP_CC) -r:clearsilver.dll -unsafe csperftest.cs perf: csperftest.exe export LD_LIBRARY_PATH=../dso; \ $(MONO_JIT) csperftest.exe testcs: cstest.exe @echo "Running csharp test" @failed=0; \ rm -f cstest.out; \ export LD_LIBRARY_PATH=../dso; \ $(MONO_JIT) cstest.exe > cstest.out; \ diff cstest.out cstest.gold > /dev/null; \ return_code=$$?; \ if [ $$return_code -ne 0 ]; then \ diff cstest.out cstest.gold > cstest.err; \ echo "Failed csharp test: cstest.cs"; \ echo " See cstest.out and cstest.err"; \ failed=1; \ fi; \ if [ $$failed -eq 1 ]; then \ exit 1; \ fi; @echo "Passed csharp test" gold: cstest.exe export LD_LIBRARY_PATH=../dso; \ $(MONO_JIT) cstest.exe > cstest.gold; @echo "Generated gold files" clean: rm -f core.* distclean: rm -f $(TARGETS) core.* Makefile.depend clearsilver-0.10.5/csharp/README0000644001211700116100000000240310261037511013157 00000000000000################################# # # C# Clearsilver wrapper # # David Jeske # This wrapper was developed using the Mono project's C# implementation. It isn't done, and it hasn't yet been tested with the MS C# implementation, however, in theory it should work. Here are some salient ideas behind this implementation: - I don't use IntPtr, because it is basically a void* that removes type information and begs for coredumps to occur later. - I also don't use data marshaling for aggregate C-types. Instead I merely access the structure members directly from C# unsafe code, just like you would if this was C code. - The only data which is marshalled is function arguments and data which is pulled out of or put into C-structures. - There are many things still todo before this is a fully working module, but the basics are there. TODO: - more tests (look at ruby/test/hdftest.rb for an example) - do something better about mapping hdferror to exceptions - recheck the function prototypes to make sure I'm handling all arguments - handle next(), prev() - make iterator for child nodes - allow registration of upload callbacks and data-formatters from C# - open up access to other parts of cgi and util - sample code for using inside mod_mono, includign CSPage.cs clearsilver-0.10.5/csharp/csperftest.cs0000644001211700116100000000226010261037511015011 00000000000000using System; using System.Runtime.InteropServices; using Clearsilver; public class CSPerfTest { public delegate void test_function(int INDEX); public static void timefunk(String label, test_function f, int count) { int start, end, elapsed; start = Environment.TickCount; f(count); end = Environment.TickCount; elapsed = end-start; Console.WriteLine(label + " " + count + " elapsed: " + (elapsed / 1000.0)); } public static unsafe int Main(string[] argv) { Console.WriteLine("C# Clearsilver wrapper performance test"); Hdf h = new Hdf(); h.setValue("foo.1","1"); h.setValue("foo.2","2"); int call_count = 100000; int start = Environment.TickCount; for (int i=0;i clearsilver-0.10.5/csharp/data_cstest.hdf0000644001211700116100000000000410261037511015253 00000000000000a=1 clearsilver-0.10.5/ports/0000755001211700116100000000000010645505045012257 500000000000000clearsilver-0.10.5/ports/freebsd/0000755001211700116100000000000010645505045013671 500000000000000clearsilver-0.10.5/ports/freebsd/Makefile0000644001211700116100000000134310261037513015244 00000000000000# New ports collection makefile for: clearsilver # Date created: 13 April 2003 # Whom: Brandon Long # # $FreeBSD$ # PORTNAME= clearsilver PORTVERSION= 0.9.7 CATEGORIES= www python perl ruby DISTDIR= /home/blong/ports/distfiles MASTER_SITES= http://www.clearsilver.net/downloads/ MAINTAINER= blong@fiction.net COMMENT= ClearSilver is a fast, powerful, and language-neutral HTML template system. .if defined(PACKAGE_BUILDING) WITH_PERL= yes WITH_PYTHON= yes .endif .if defined(WITH_PYTHON) USE_PYTHON= yes .endif .if defined(WITH_PERL) USE_PERL5= yes .endif .if defined(WITH_RUBY) USE_RUBY= yes .endif GNU_CONFIGURE= yes USE_GMAKE= yes .include clearsilver-0.10.5/ports/freebsd/pkg-descr0000644001211700116100000000101010261037513015375 00000000000000 ClearSilver is a fast, powerful, and language-neutral HTML template system. In both static content sites and dynamic HTML applications, it provides a separation between presentation code and application logic which makes working with your project easier. Because it's written as a C-library, and exported to scripting languages like Python, Perl, and Ruby via modules, it is extremely fast compared to template systems written in a script language. WWW: http://www.clearsilver.net/ - Brandon blong@fiction.net clearsilver-0.10.5/ports/freebsd/pkg-plist0000644001211700116100000000112510261037513015437 00000000000000ClearSilver.h cs_config.h cgi/cgi.h cgi/cgiwrap.h cgi/date.h cgi/html.h cs/cs.h util/dict.h util/filter.h util/neo_date.h util/neo_err.h util/neo_files.h util/neo_hash.h util/neo_hdf.h util/neo_misc.h* util/neo_net.h util/neo_rand.h util/neo_server.h util/neo_str.h util/rcfs.h util/skiplist.h util/ulist.h util/ulocks.h util/wdb.h util/wildmat.h lib/libneo_cgi.a lib/libneo_cs.a lib/libneo_utl.a bin/static.cgi bin/cstest %%PYTHON_SITELIBDIR%%/neo_cgi.so lib/perl5/site_perl/%%PERL_VER%%/%%PERL_ARCH%%/ClearSilver.pm lib/perl5/site_perl/%%PERL_VER%%/%%PERL_ARCH%%/auto/ClearSilver/ClearSilver.so clearsilver-0.10.5/ports/rpm/0000755001211700116100000000000010645505045013055 500000000000000clearsilver-0.10.5/ports/rpm/clearsilver.spec0000644001211700116100000001624210645312537016173 00000000000000# # spec file for ClearSilver Linux RPM (based on RedHat installs) # # Caveats: There is some difficulty getting this file to sync with the # actual information discovered by configure. In theory, some of this # stuff in here could be driven off of configure.. except that configure # is supposed to be driven off this file... # # * PREFIX vs perl/python PREFIX: where the perl/python modules get # installed is actually defined by the installation of perl/python you # are using to build the module. For that reason, we need to use a # different PREFIX for the python/perl modules. For python, we just # override PYTHON_SITE during install, for perl we have to run make # install again with a new PREFIX. This means the perl module might be # installed in two different locations, but we just package the second # one. # # * The perl suggestions for rpms: # http://archive.develooper.com/perl-dist@perl.org/msg00055.html # suggest using find to get all of the files for the perl module. I'm # currently hard coding them since we're not just building the perl # module. In particular, the file path of the ClearSilver.3pm.gz # manpage is probably wrong on some platforms. # # * The apache/java/ruby/csharp packages are not yet finished. For one, # all of my machines are redhat 7.3 or earlier, and don't have rpms # installed for java/ruby/csharp, and my apache installation is Neotonic # specific and therefore not much help to the rest of you. ########################################################################## ## Edit these settings %define __prefix /usr/local %define __python /usr/bin/python %define with_python_subpackage 1 %{nil} %define with_perl_subpackage 1 %{nil} # These packages aren't tested at all and probably won't build %define with_apache_subpackage 0 %define with_java_subpackage 0 %define with_ruby_subpackage 0 %define with_csharp_subpackage 0 ########################################################################## ## All of the rest of this should work correctly based on the top... ## maybe %define python_sitepath %(%{__python} -c "import site; print site.sitedirs[0]") %define perl_sitearch %(eval "`perl -V:installsitearch`"; echo $installsitearch) %define perl_prefix %(eval "`perl -V:prefix`"; echo $prefix) %define ruby_sitepath %(echo "i dunno") %define ruby_version %(echo "i dunno") %define ruby_arch %(echo "i dunno") %define apache_libexec %(eval `/httpd/bin/apxs -q LIBEXECDIR`) Summary: Neotonic ClearSilver Name: clearsilver Version: 0.10.5 Release: 1 Copyright: Open Source - Neotonic ClearSilver License (Apache 1.1 based) Group: Development/Libraries Source: http://www.clearsilver.net/downloads/clearsilver-0.10.5.tar.gz URL: http://www.clearsilver.net/ Vendor: Neotonic Software Corporation, Inc. Packager: Brandon Long BuildRequires: zlib-devel %if %{with_python_subpackage} BuildRequires: python-devel >= 1.5.2 %endif %if %{with_perl_subpackage} BuildRequires: perl >= 0:5.006 %endif %if %{with_ruby_subpackage} BuildRequires: ruby >= 1.4.5 %endif BuildRoot: %{_tmppath}/%{name}-root %description ClearSilver is a fast, powerful, and language-neutral HTML template system. In both static content sites and dynamic HTML applications, it provides a separation between presentation code and application logic which makes working with your project easier. Because it's written as a C-library, and exported to scripting languages like Python and Perl via modules, it is extremely fast compared to template systems written in a script language. %if %{with_python_subpackage} %package python Summary: Neotonic ClearSilver Python Module Group: Development/Libraries Requires: clearsilver = %PACKAGE_VERSION %requires_eq python %description python The clearsilver-python package provides a python interface to the clearsilver CGI kit and templating system. %endif %if %{with_perl_subpackage} %package perl Summary: Neotonic ClearSilver Perl Module Group: Development/Libraries Requires: clearsilver = %PACKAGE_VERSION Requires: perl >= 0:5.006 %requires_eq perl %description perl The clearsilver-perl package provides a perl interface to the clearsilver templating system. %endif %if %{with_ruby_subpackage} %package ruby Summary: Neotonic ClearSilver Ruby Module Group: Development/Libraries Requires: clearsilver = %PACKAGE_VERSION Requires: ruby >= 1.4.5 %description ruby The clearsilver-ruby package provides a ruby interface to the clearsilver templating system. %endif %if %{with_apache_subpackage} %package apache Summary: Neotonic ClearSilver Apache Module Group: Development/Libraries Requires: clearsilver = %PACKAGE_VERSION Requires: apache >= 1.3.0 Requires: apache < 1.4 %description apache The clearsilver-apache package provides an Apache 1.3.x module for loading ClearSilver CGI's as shared libraries. %endif %if %{with_java_subpackage} %package java Group: Development/Libraries Requires: clearsilver = %PACKAGE_VERSION %description java The clearsilver-java package provides a java jni interface to the clearsilver templating system. %endif %prep %setup %build ./configure --prefix=%{__prefix} --with-python=%{__python} make %install make PREFIX="$RPM_BUILD_ROOT%{__prefix}" prefix="$RPM_BUILD_ROOT%{__prefix}" PYTHON_SITE="$RPM_BUILD_ROOT%{python_sitepath}" install cd perl make PREFIX="$RPM_BUILD_ROOT%{perl_prefix}" install cd .. %files %{__prefix}/include/ClearSilver/ClearSilver.h %{__prefix}/include/ClearSilver/cs_config.h %{__prefix}/include/ClearSilver/cgi/cgi.h %{__prefix}/include/ClearSilver/cgi/cgiwrap.h %{__prefix}/include/ClearSilver/cgi/date.h %{__prefix}/include/ClearSilver/cgi/html.h %{__prefix}/include/ClearSilver/cs/cs.h %{__prefix}/include/ClearSilver/util/dict.h %{__prefix}/include/ClearSilver/util/filter.h %{__prefix}/include/ClearSilver/util/neo_date.h %{__prefix}/include/ClearSilver/util/neo_err.h %{__prefix}/include/ClearSilver/util/neo_files.h %{__prefix}/include/ClearSilver/util/neo_hash.h %{__prefix}/include/ClearSilver/util/neo_hdf.h %{__prefix}/include/ClearSilver/util/neo_misc.h %{__prefix}/include/ClearSilver/util/neo_net.h %{__prefix}/include/ClearSilver/util/neo_rand.h %{__prefix}/include/ClearSilver/util/neo_server.h %{__prefix}/include/ClearSilver/util/neo_str.h %{__prefix}/include/ClearSilver/util/rcfs.h %{__prefix}/include/ClearSilver/util/skiplist.h %{__prefix}/include/ClearSilver/util/ulist.h %{__prefix}/include/ClearSilver/util/ulocks.h %{__prefix}/include/ClearSilver/util/wdb.h %{__prefix}/include/ClearSilver/util/wildmat.h %{__prefix}/lib/libneo_cgi.a %{__prefix}/lib/libneo_cs.a %{__prefix}/lib/libneo_utl.a %{__prefix}/bin/static.cgi %{__prefix}/bin/cstest %{__prefix}/man/man3 %if %{with_python_subpackage} %files python %{python_sitepath}/neo_cgi.so %endif %if %{with_perl_subpackage} %files perl %{perl_sitearch}/ClearSilver.pm %{perl_sitearch}/auto/ClearSilver/ClearSilver.so %{perl_sitearch}/auto/ClearSilver/ClearSilver.bs %{perl_prefix}/share/man/man3/ClearSilver.3pm.gz %endif %if %{with_ruby_subpackage} %files ruby %{ruby_sitepath}/%(ruby_version}/neo.rb %{ruby_sitepath}/%(ruby_version}/$(ruby_arch}/hdf.so %endif %if %{with_apache_subpackage} %files apache %{apache_libexec}/mod_ecs.so %endif %if %{with_java_subpackage} %files java %{__prefix}/lib/clearsilver.jar %{__prefix}/lib/libclearsilver-jni.so %endif clearsilver-0.10.5/contrib/0000755001211700116100000000000010645505045012550 500000000000000clearsilver-0.10.5/contrib/cs-mode.el0000644001211700116100000000236210261037504014336 00000000000000(defvar cs-font-lock-keywords (list '("<\\?cs[^\\?]*\\?>" 0 font-lock-keyword-face t) '("<\\?cs +\\(call\\|each\\|if\\|alt\\|var\\|include\\)" 1 font-lock-keyword-face t) '("<\\?cs +\\(/each\\|/if\\|/alt\\|/var\\|/include\\)" 1 font-lock-keyword-face t) ; variable names '("<\\?cs +var:\\([_0-9a-zA-Z\.]+\\)[^\\?]+\\?>" 1 font-lock-variable-name-face t) '("<\\?cs +alt:\\([_0-9a-zA-Z\.]+\\)[^\\?]+\\?>" 1 font-lock-variable-name-face t) '("<\\?cs +each:\\([_0-9a-zA-Z\.]+\\)[^\\?]+\\?>" 1 font-lock-variable-name-face t) ; string '("<\\?cs[^\"\\?]+\\(\"[^\"]+\"\\)[^\\?]+\\?>" 1 font-lock-string-face t) )) (defvar cs-mode-map ()) (if (not cs-mode-map) (progn (setq cs-mode-map (make-sparse-keymap)) (define-key cs-mode-map "\C-c\C-i" 'cs-insert-tag) )) (defun cs-mode nil "ClearSilver mode" (interactive) (setq major-mode 'cs-mode) (setq mode-name "CS") (use-local-map cs-mode-map) (make-local-variable 'font-lock-defaults) (setq font-lock-defaults '((cs-font-lock-keywords) t)) (setq font-lock-keywords cs-font-lock-keywords) (font-lock-mode 1) (run-hooks 'cs-mode-hook) ) (defun cs-insert-tag () (interactive) (insert "") (backward-char 3) ) clearsilver-0.10.5/m4/0000755001211700116100000000000010645505045011430 500000000000000clearsilver-0.10.5/m4/ac_jni_include_dirs.m40000644001211700116100000000626110336776331015573 00000000000000dnl @synopsis AC_JNI_INCLUDE_DIR dnl dnl AC_JNI_INCLUDE_DIR finds include directories needed dnl for compiling programs using the JNI interface. dnl dnl JNI include directories are usually in the java distribution dnl This is deduced from the value of JAVAC. When this macro dnl completes, a list of directories is left in the variable dnl JNI_INCLUDE_DIRS. dnl dnl Example usage follows: dnl dnl AC_JNI_INCLUDE_DIR dnl dnl for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS dnl do dnl CPPFLAGS="$CPPFLAGS -I$JNI_INCLUDE_DIR" dnl done dnl dnl If you want to force a specific compiler: dnl dnl - at the configure.in level, set JAVAC=yourcompiler before calling dnl AC_JNI_INCLUDE_DIR dnl dnl - at the configure level, setenv JAVAC dnl dnl Note: This macro can work with the autoconf M4 macros for Java programs. dnl This particular macro is not part of the original set of macros. dnl dnl @author Don Anderson dnl @version $Id: ac_jni_include_dirs.m4,v 1.3 2004/12/24 01:16:37 guidod Exp $ dnl AC_DEFUN([AC_JNI_INCLUDE_DIR],[ JNI_INCLUDE_DIRS="" test "x$JAVAC" = x && AC_MSG_ERROR(['$JAVAC' undefined]) AC_PATH_PROG(_ACJNI_JAVAC, $JAVAC, no) test "x$_ACJNI_JAVAC" = xno && AC_MSG_ERROR([$JAVAC could not be found in path]) _ACJNI_FOLLOW_SYMLINKS("$_ACJNI_JAVAC") _JTOPDIR=`echo "$_ACJNI_FOLLOWED" | sed -e 's://*:/:g' -e 's:/[[^/]]*$::'` case "$host_os" in darwin*) _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'` _JINC="$_JTOPDIR/Headers";; *) _JINC="$_JTOPDIR/include";; esac if test -f "$_JINC/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JINC" else _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'` if test -f "$_JTOPDIR/include/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include" else AC_MSG_ERROR([cannot find java include files]) fi fi # get the likely subdirectories for system specific java includes case "$host_os" in bsdi*) _JNI_INC_SUBDIRS="bsdos";; linux*) _JNI_INC_SUBDIRS="linux genunix";; osf*) _JNI_INC_SUBDIRS="alpha";; solaris*) _JNI_INC_SUBDIRS="solaris";; mingw*) _JNI_INC_SUBDIRS="win32";; cygwin*) _JNI_INC_SUBDIRS="win32";; *) _JNI_INC_SUBDIRS="genunix";; esac # add any subdirectories that are present for JINCSUBDIR in $_JNI_INC_SUBDIRS do if test -d "$_JTOPDIR/include/$JINCSUBDIR"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include/$JINCSUBDIR" fi done ]) # _ACJNI_FOLLOW_SYMLINKS # Follows symbolic links on , # finally setting variable _ACJNI_FOLLOWED # -------------------- AC_DEFUN([_ACJNI_FOLLOW_SYMLINKS],[ # find the include directory relative to the javac executable _cur="$1" while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do AC_MSG_CHECKING(symlink for $_cur) _slink=`ls -ld "$_cur" | sed 's/.* -> //'` case "$_slink" in /*) _cur="$_slink";; # 'X' avoids triggering unwanted echo options. *) _cur=`echo "X$_cur" | sed -e 's/^X//' -e 's:[[^/]]*$::'`"$_slink";; esac AC_MSG_RESULT($_cur) done _ACJNI_FOLLOWED="$_cur" ])# _ACJNI clearsilver-0.10.5/aclocal.m40000644001211700116100000010603010645505045012670 00000000000000dnl aclocal.m4 generated automatically by aclocal 1.4-p6 dnl Copyright (C) 1994, 1995-8, 1999, 2001 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. dnl This program is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY, to the extent permitted by law; without dnl even the implied warranty of MERCHANTABILITY or FITNESS FOR A dnl PARTICULAR PURPOSE. # lib-prefix.m4 serial 4 (gettext-0.14.2) dnl Copyright (C) 2001-2005 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. dnl From Bruno Haible. dnl AC_LIB_ARG_WITH is synonymous to AC_ARG_WITH in autoconf-2.13, and dnl similar to AC_ARG_WITH in autoconf 2.52...2.57 except that is doesn't dnl require excessive bracketing. ifdef([AC_HELP_STRING], [AC_DEFUN([AC_LIB_ARG_WITH], [AC_ARG_WITH([$1],[[$2]],[$3],[$4])])], [AC_DEFUN([AC_][LIB_ARG_WITH], [AC_ARG_WITH([$1],[$2],[$3],[$4])])]) dnl AC_LIB_PREFIX adds to the CPPFLAGS and LDFLAGS the flags that are needed dnl to access previously installed libraries. The basic assumption is that dnl a user will want packages to use other packages he previously installed dnl with the same --prefix option. dnl This macro is not needed if only AC_LIB_LINKFLAGS is used to locate dnl libraries, but is otherwise very convenient. AC_DEFUN([AC_LIB_PREFIX], [ AC_BEFORE([$0], [AC_LIB_LINKFLAGS]) AC_REQUIRE([AC_PROG_CC]) AC_REQUIRE([AC_CANONICAL_HOST]) AC_REQUIRE([AC_LIB_PREPARE_PREFIX]) dnl By default, look in $includedir and $libdir. use_additional=yes AC_LIB_WITH_FINAL_PREFIX([ eval additional_includedir=\"$includedir\" eval additional_libdir=\"$libdir\" ]) AC_LIB_ARG_WITH([lib-prefix], [ --with-lib-prefix[=DIR] search for libraries in DIR/include and DIR/lib --without-lib-prefix don't search for libraries in includedir and libdir], [ if test "X$withval" = "Xno"; then use_additional=no else if test "X$withval" = "X"; then AC_LIB_WITH_FINAL_PREFIX([ eval additional_includedir=\"$includedir\" eval additional_libdir=\"$libdir\" ]) else additional_includedir="$withval/include" additional_libdir="$withval/lib" fi fi ]) if test $use_additional = yes; then dnl Potentially add $additional_includedir to $CPPFLAGS. dnl But don't add it dnl 1. if it's the standard /usr/include, dnl 2. if it's already present in $CPPFLAGS, dnl 3. if it's /usr/local/include and we are using GCC on Linux, dnl 4. if it doesn't exist as a directory. if test "X$additional_includedir" != "X/usr/include"; then haveit= for x in $CPPFLAGS; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X-I$additional_includedir"; then haveit=yes break fi done if test -z "$haveit"; then if test "X$additional_includedir" = "X/usr/local/include"; then if test -n "$GCC"; then case $host_os in linux* | gnu* | k*bsd*-gnu) haveit=yes;; esac fi fi if test -z "$haveit"; then if test -d "$additional_includedir"; then dnl Really add $additional_includedir to $CPPFLAGS. CPPFLAGS="${CPPFLAGS}${CPPFLAGS:+ }-I$additional_includedir" fi fi fi fi dnl Potentially add $additional_libdir to $LDFLAGS. dnl But don't add it dnl 1. if it's the standard /usr/lib, dnl 2. if it's already present in $LDFLAGS, dnl 3. if it's /usr/local/lib and we are using GCC on Linux, dnl 4. if it doesn't exist as a directory. if test "X$additional_libdir" != "X/usr/lib"; then haveit= for x in $LDFLAGS; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X-L$additional_libdir"; then haveit=yes break fi done if test -z "$haveit"; then if test "X$additional_libdir" = "X/usr/local/lib"; then if test -n "$GCC"; then case $host_os in linux*) haveit=yes;; esac fi fi if test -z "$haveit"; then if test -d "$additional_libdir"; then dnl Really add $additional_libdir to $LDFLAGS. LDFLAGS="${LDFLAGS}${LDFLAGS:+ }-L$additional_libdir" fi fi fi fi fi ]) dnl AC_LIB_PREPARE_PREFIX creates variables acl_final_prefix, dnl acl_final_exec_prefix, containing the values to which $prefix and dnl $exec_prefix will expand at the end of the configure script. AC_DEFUN([AC_LIB_PREPARE_PREFIX], [ dnl Unfortunately, prefix and exec_prefix get only finally determined dnl at the end of configure. if test "X$prefix" = "XNONE"; then acl_final_prefix="$ac_default_prefix" else acl_final_prefix="$prefix" fi if test "X$exec_prefix" = "XNONE"; then acl_final_exec_prefix='${prefix}' else acl_final_exec_prefix="$exec_prefix" fi acl_save_prefix="$prefix" prefix="$acl_final_prefix" eval acl_final_exec_prefix=\"$acl_final_exec_prefix\" prefix="$acl_save_prefix" ]) dnl AC_LIB_WITH_FINAL_PREFIX([statement]) evaluates statement, with the dnl variables prefix and exec_prefix bound to the values they will have dnl at the end of the configure script. AC_DEFUN([AC_LIB_WITH_FINAL_PREFIX], [ acl_save_prefix="$prefix" prefix="$acl_final_prefix" acl_save_exec_prefix="$exec_prefix" exec_prefix="$acl_final_exec_prefix" $1 exec_prefix="$acl_save_exec_prefix" prefix="$acl_save_prefix" ]) # lib-link.m4 serial 6 (gettext-0.14.3) dnl Copyright (C) 2001-2005 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. dnl From Bruno Haible. AC_PREREQ(2.50) dnl AC_LIB_LINKFLAGS(name [, dependencies]) searches for libname and dnl the libraries corresponding to explicit and implicit dependencies. dnl Sets and AC_SUBSTs the LIB${NAME} and LTLIB${NAME} variables and dnl augments the CPPFLAGS variable. AC_DEFUN([AC_LIB_LINKFLAGS], [ AC_REQUIRE([AC_LIB_PREPARE_PREFIX]) AC_REQUIRE([AC_LIB_RPATH]) define([Name],[translit([$1],[./-], [___])]) define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-], [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])]) AC_CACHE_CHECK([how to link with lib[]$1], [ac_cv_lib[]Name[]_libs], [ AC_LIB_LINKFLAGS_BODY([$1], [$2]) ac_cv_lib[]Name[]_libs="$LIB[]NAME" ac_cv_lib[]Name[]_ltlibs="$LTLIB[]NAME" ac_cv_lib[]Name[]_cppflags="$INC[]NAME" ]) LIB[]NAME="$ac_cv_lib[]Name[]_libs" LTLIB[]NAME="$ac_cv_lib[]Name[]_ltlibs" INC[]NAME="$ac_cv_lib[]Name[]_cppflags" AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME) AC_SUBST([LIB]NAME) AC_SUBST([LTLIB]NAME) dnl Also set HAVE_LIB[]NAME so that AC_LIB_HAVE_LINKFLAGS can reuse the dnl results of this search when this library appears as a dependency. HAVE_LIB[]NAME=yes undefine([Name]) undefine([NAME]) ]) dnl AC_LIB_HAVE_LINKFLAGS(name, dependencies, includes, testcode) dnl searches for libname and the libraries corresponding to explicit and dnl implicit dependencies, together with the specified include files and dnl the ability to compile and link the specified testcode. If found, it dnl sets and AC_SUBSTs HAVE_LIB${NAME}=yes and the LIB${NAME} and dnl LTLIB${NAME} variables and augments the CPPFLAGS variable, and dnl #defines HAVE_LIB${NAME} to 1. Otherwise, it sets and AC_SUBSTs dnl HAVE_LIB${NAME}=no and LIB${NAME} and LTLIB${NAME} to empty. AC_DEFUN([AC_LIB_HAVE_LINKFLAGS], [ AC_REQUIRE([AC_LIB_PREPARE_PREFIX]) AC_REQUIRE([AC_LIB_RPATH]) define([Name],[translit([$1],[./-], [___])]) define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-], [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])]) dnl Search for lib[]Name and define LIB[]NAME, LTLIB[]NAME and INC[]NAME dnl accordingly. AC_LIB_LINKFLAGS_BODY([$1], [$2]) dnl Add $INC[]NAME to CPPFLAGS before performing the following checks, dnl because if the user has installed lib[]Name and not disabled its use dnl via --without-lib[]Name-prefix, he wants to use it. ac_save_CPPFLAGS="$CPPFLAGS" AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME) AC_CACHE_CHECK([for lib[]$1], [ac_cv_lib[]Name], [ ac_save_LIBS="$LIBS" LIBS="$LIBS $LIB[]NAME" AC_TRY_LINK([$3], [$4], [ac_cv_lib[]Name=yes], [ac_cv_lib[]Name=no]) LIBS="$ac_save_LIBS" ]) if test "$ac_cv_lib[]Name" = yes; then HAVE_LIB[]NAME=yes AC_DEFINE([HAVE_LIB]NAME, 1, [Define if you have the $1 library.]) AC_MSG_CHECKING([how to link with lib[]$1]) AC_MSG_RESULT([$LIB[]NAME]) else HAVE_LIB[]NAME=no dnl If $LIB[]NAME didn't lead to a usable library, we don't need dnl $INC[]NAME either. CPPFLAGS="$ac_save_CPPFLAGS" LIB[]NAME= LTLIB[]NAME= fi AC_SUBST([HAVE_LIB]NAME) AC_SUBST([LIB]NAME) AC_SUBST([LTLIB]NAME) undefine([Name]) undefine([NAME]) ]) dnl Determine the platform dependent parameters needed to use rpath: dnl libext, shlibext, hardcode_libdir_flag_spec, hardcode_libdir_separator, dnl hardcode_direct, hardcode_minus_L. AC_DEFUN([AC_LIB_RPATH], [ dnl Tell automake >= 1.10 to complain if config.rpath is missing. m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([config.rpath])]) AC_REQUIRE([AC_PROG_CC]) dnl we use $CC, $GCC, $LDFLAGS AC_REQUIRE([AC_LIB_PROG_LD]) dnl we use $LD, $with_gnu_ld AC_REQUIRE([AC_CANONICAL_HOST]) dnl we use $host AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT]) dnl we use $ac_aux_dir AC_CACHE_CHECK([for shared library run path origin], acl_cv_rpath, [ CC="$CC" GCC="$GCC" LDFLAGS="$LDFLAGS" LD="$LD" with_gnu_ld="$with_gnu_ld" \ ${CONFIG_SHELL-/bin/sh} "$ac_aux_dir/config.rpath" "$host" > conftest.sh . ./conftest.sh rm -f ./conftest.sh acl_cv_rpath=done ]) wl="$acl_cv_wl" libext="$acl_cv_libext" shlibext="$acl_cv_shlibext" hardcode_libdir_flag_spec="$acl_cv_hardcode_libdir_flag_spec" hardcode_libdir_separator="$acl_cv_hardcode_libdir_separator" hardcode_direct="$acl_cv_hardcode_direct" hardcode_minus_L="$acl_cv_hardcode_minus_L" dnl Determine whether the user wants rpath handling at all. AC_ARG_ENABLE(rpath, [ --disable-rpath do not hardcode runtime library paths], :, enable_rpath=yes) ]) dnl AC_LIB_LINKFLAGS_BODY(name [, dependencies]) searches for libname and dnl the libraries corresponding to explicit and implicit dependencies. dnl Sets the LIB${NAME}, LTLIB${NAME} and INC${NAME} variables. AC_DEFUN([AC_LIB_LINKFLAGS_BODY], [ define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-], [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])]) dnl By default, look in $includedir and $libdir. use_additional=yes AC_LIB_WITH_FINAL_PREFIX([ eval additional_includedir=\"$includedir\" eval additional_libdir=\"$libdir\" ]) AC_LIB_ARG_WITH([lib$1-prefix], [ --with-lib$1-prefix[=DIR] search for lib$1 in DIR/include and DIR/lib --without-lib$1-prefix don't search for lib$1 in includedir and libdir], [ if test "X$withval" = "Xno"; then use_additional=no else if test "X$withval" = "X"; then AC_LIB_WITH_FINAL_PREFIX([ eval additional_includedir=\"$includedir\" eval additional_libdir=\"$libdir\" ]) else additional_includedir="$withval/include" additional_libdir="$withval/lib" fi fi ]) dnl Search the library and its dependencies in $additional_libdir and dnl $LDFLAGS. Using breadth-first-seach. LIB[]NAME= LTLIB[]NAME= INC[]NAME= rpathdirs= ltrpathdirs= names_already_handled= names_next_round='$1 $2' while test -n "$names_next_round"; do names_this_round="$names_next_round" names_next_round= for name in $names_this_round; do already_handled= for n in $names_already_handled; do if test "$n" = "$name"; then already_handled=yes break fi done if test -z "$already_handled"; then names_already_handled="$names_already_handled $name" dnl See if it was already located by an earlier AC_LIB_LINKFLAGS dnl or AC_LIB_HAVE_LINKFLAGS call. uppername=`echo "$name" | sed -e 'y|abcdefghijklmnopqrstuvwxyz./-|ABCDEFGHIJKLMNOPQRSTUVWXYZ___|'` eval value=\"\$HAVE_LIB$uppername\" if test -n "$value"; then if test "$value" = yes; then eval value=\"\$LIB$uppername\" test -z "$value" || LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$value" eval value=\"\$LTLIB$uppername\" test -z "$value" || LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$value" else dnl An earlier call to AC_LIB_HAVE_LINKFLAGS has determined dnl that this library doesn't exist. So just drop it. : fi else dnl Search the library lib$name in $additional_libdir and $LDFLAGS dnl and the already constructed $LIBNAME/$LTLIBNAME. found_dir= found_la= found_so= found_a= if test $use_additional = yes; then if test -n "$shlibext" && test -f "$additional_libdir/lib$name.$shlibext"; then found_dir="$additional_libdir" found_so="$additional_libdir/lib$name.$shlibext" if test -f "$additional_libdir/lib$name.la"; then found_la="$additional_libdir/lib$name.la" fi else if test -f "$additional_libdir/lib$name.$libext"; then found_dir="$additional_libdir" found_a="$additional_libdir/lib$name.$libext" if test -f "$additional_libdir/lib$name.la"; then found_la="$additional_libdir/lib$name.la" fi fi fi fi if test "X$found_dir" = "X"; then for x in $LDFLAGS $LTLIB[]NAME; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) case "$x" in -L*) dir=`echo "X$x" | sed -e 's/^X-L//'` if test -n "$shlibext" && test -f "$dir/lib$name.$shlibext"; then found_dir="$dir" found_so="$dir/lib$name.$shlibext" if test -f "$dir/lib$name.la"; then found_la="$dir/lib$name.la" fi else if test -f "$dir/lib$name.$libext"; then found_dir="$dir" found_a="$dir/lib$name.$libext" if test -f "$dir/lib$name.la"; then found_la="$dir/lib$name.la" fi fi fi ;; esac if test "X$found_dir" != "X"; then break fi done fi if test "X$found_dir" != "X"; then dnl Found the library. LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$found_dir -l$name" if test "X$found_so" != "X"; then dnl Linking with a shared library. We attempt to hardcode its dnl directory into the executable's runpath, unless it's the dnl standard /usr/lib. if test "$enable_rpath" = no || test "X$found_dir" = "X/usr/lib"; then dnl No hardcoding is needed. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so" else dnl Use an explicit option to hardcode DIR into the resulting dnl binary. dnl Potentially add DIR to ltrpathdirs. dnl The ltrpathdirs will be appended to $LTLIBNAME at the end. haveit= for x in $ltrpathdirs; do if test "X$x" = "X$found_dir"; then haveit=yes break fi done if test -z "$haveit"; then ltrpathdirs="$ltrpathdirs $found_dir" fi dnl The hardcoding into $LIBNAME is system dependent. if test "$hardcode_direct" = yes; then dnl Using DIR/libNAME.so during linking hardcodes DIR into the dnl resulting binary. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so" else if test -n "$hardcode_libdir_flag_spec" && test "$hardcode_minus_L" = no; then dnl Use an explicit option to hardcode DIR into the resulting dnl binary. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so" dnl Potentially add DIR to rpathdirs. dnl The rpathdirs will be appended to $LIBNAME at the end. haveit= for x in $rpathdirs; do if test "X$x" = "X$found_dir"; then haveit=yes break fi done if test -z "$haveit"; then rpathdirs="$rpathdirs $found_dir" fi else dnl Rely on "-L$found_dir". dnl But don't add it if it's already contained in the LDFLAGS dnl or the already constructed $LIBNAME haveit= for x in $LDFLAGS $LIB[]NAME; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X-L$found_dir"; then haveit=yes break fi done if test -z "$haveit"; then LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir" fi if test "$hardcode_minus_L" != no; then dnl FIXME: Not sure whether we should use dnl "-L$found_dir -l$name" or "-L$found_dir $found_so" dnl here. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so" else dnl We cannot use $hardcode_runpath_var and LD_RUN_PATH dnl here, because this doesn't fit in flags passed to the dnl compiler. So give up. No hardcoding. This affects only dnl very old systems. dnl FIXME: Not sure whether we should use dnl "-L$found_dir -l$name" or "-L$found_dir $found_so" dnl here. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name" fi fi fi fi else if test "X$found_a" != "X"; then dnl Linking with a static library. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_a" else dnl We shouldn't come here, but anyway it's good to have a dnl fallback. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir -l$name" fi fi dnl Assume the include files are nearby. additional_includedir= case "$found_dir" in */lib | */lib/) basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e 's,/lib/*$,,'` additional_includedir="$basedir/include" ;; esac if test "X$additional_includedir" != "X"; then dnl Potentially add $additional_includedir to $INCNAME. dnl But don't add it dnl 1. if it's the standard /usr/include, dnl 2. if it's /usr/local/include and we are using GCC on Linux, dnl 3. if it's already present in $CPPFLAGS or the already dnl constructed $INCNAME, dnl 4. if it doesn't exist as a directory. if test "X$additional_includedir" != "X/usr/include"; then haveit= if test "X$additional_includedir" = "X/usr/local/include"; then if test -n "$GCC"; then case $host_os in linux* | gnu* | k*bsd*-gnu) haveit=yes;; esac fi fi if test -z "$haveit"; then for x in $CPPFLAGS $INC[]NAME; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X-I$additional_includedir"; then haveit=yes break fi done if test -z "$haveit"; then if test -d "$additional_includedir"; then dnl Really add $additional_includedir to $INCNAME. INC[]NAME="${INC[]NAME}${INC[]NAME:+ }-I$additional_includedir" fi fi fi fi fi dnl Look for dependencies. if test -n "$found_la"; then dnl Read the .la file. It defines the variables dnl dlname, library_names, old_library, dependency_libs, current, dnl age, revision, installed, dlopen, dlpreopen, libdir. save_libdir="$libdir" case "$found_la" in */* | *\\*) . "$found_la" ;; *) . "./$found_la" ;; esac libdir="$save_libdir" dnl We use only dependency_libs. for dep in $dependency_libs; do case "$dep" in -L*) additional_libdir=`echo "X$dep" | sed -e 's/^X-L//'` dnl Potentially add $additional_libdir to $LIBNAME and $LTLIBNAME. dnl But don't add it dnl 1. if it's the standard /usr/lib, dnl 2. if it's /usr/local/lib and we are using GCC on Linux, dnl 3. if it's already present in $LDFLAGS or the already dnl constructed $LIBNAME, dnl 4. if it doesn't exist as a directory. if test "X$additional_libdir" != "X/usr/lib"; then haveit= if test "X$additional_libdir" = "X/usr/local/lib"; then if test -n "$GCC"; then case $host_os in linux* | gnu* | k*bsd*-gnu) haveit=yes;; esac fi fi if test -z "$haveit"; then haveit= for x in $LDFLAGS $LIB[]NAME; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X-L$additional_libdir"; then haveit=yes break fi done if test -z "$haveit"; then if test -d "$additional_libdir"; then dnl Really add $additional_libdir to $LIBNAME. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$additional_libdir" fi fi haveit= for x in $LDFLAGS $LTLIB[]NAME; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X-L$additional_libdir"; then haveit=yes break fi done if test -z "$haveit"; then if test -d "$additional_libdir"; then dnl Really add $additional_libdir to $LTLIBNAME. LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$additional_libdir" fi fi fi fi ;; -R*) dir=`echo "X$dep" | sed -e 's/^X-R//'` if test "$enable_rpath" != no; then dnl Potentially add DIR to rpathdirs. dnl The rpathdirs will be appended to $LIBNAME at the end. haveit= for x in $rpathdirs; do if test "X$x" = "X$dir"; then haveit=yes break fi done if test -z "$haveit"; then rpathdirs="$rpathdirs $dir" fi dnl Potentially add DIR to ltrpathdirs. dnl The ltrpathdirs will be appended to $LTLIBNAME at the end. haveit= for x in $ltrpathdirs; do if test "X$x" = "X$dir"; then haveit=yes break fi done if test -z "$haveit"; then ltrpathdirs="$ltrpathdirs $dir" fi fi ;; -l*) dnl Handle this in the next round. names_next_round="$names_next_round "`echo "X$dep" | sed -e 's/^X-l//'` ;; *.la) dnl Handle this in the next round. Throw away the .la's dnl directory; it is already contained in a preceding -L dnl option. names_next_round="$names_next_round "`echo "X$dep" | sed -e 's,^X.*/,,' -e 's,^lib,,' -e 's,\.la$,,'` ;; *) dnl Most likely an immediate library name. LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$dep" LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$dep" ;; esac done fi else dnl Didn't find the library; assume it is in the system directories dnl known to the linker and runtime loader. (All the system dnl directories known to the linker should also be known to the dnl runtime loader, otherwise the system is severely misconfigured.) LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name" LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-l$name" fi fi fi done done if test "X$rpathdirs" != "X"; then if test -n "$hardcode_libdir_separator"; then dnl Weird platform: only the last -rpath option counts, the user must dnl pass all path elements in one option. We can arrange that for a dnl single library, but not when more than one $LIBNAMEs are used. alldirs= for found_dir in $rpathdirs; do alldirs="${alldirs}${alldirs:+$hardcode_libdir_separator}$found_dir" done dnl Note: hardcode_libdir_flag_spec uses $libdir and $wl. acl_save_libdir="$libdir" libdir="$alldirs" eval flag=\"$hardcode_libdir_flag_spec\" libdir="$acl_save_libdir" LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag" else dnl The -rpath options are cumulative. for found_dir in $rpathdirs; do acl_save_libdir="$libdir" libdir="$found_dir" eval flag=\"$hardcode_libdir_flag_spec\" libdir="$acl_save_libdir" LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag" done fi fi if test "X$ltrpathdirs" != "X"; then dnl When using libtool, the option that works for both libraries and dnl executables is -R. The -R options are cumulative. for found_dir in $ltrpathdirs; do LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-R$found_dir" done fi ]) dnl AC_LIB_APPENDTOVAR(VAR, CONTENTS) appends the elements of CONTENTS to VAR, dnl unless already present in VAR. dnl Works only for CPPFLAGS, not for LIB* variables because that sometimes dnl contains two or three consecutive elements that belong together. AC_DEFUN([AC_LIB_APPENDTOVAR], [ for element in [$2]; do haveit= for x in $[$1]; do AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"]) if test "X$x" = "X$element"; then haveit=yes break fi done if test -z "$haveit"; then [$1]="${[$1]}${[$1]:+ }$element" fi done ]) # lib-ld.m4 serial 3 (gettext-0.13) dnl Copyright (C) 1996-2003 Free Software Foundation, Inc. dnl This file is free software; the Free Software Foundation dnl gives unlimited permission to copy and/or distribute it, dnl with or without modifications, as long as this notice is preserved. dnl Subroutines of libtool.m4, dnl with replacements s/AC_/AC_LIB/ and s/lt_cv/acl_cv/ to avoid collision dnl with libtool.m4. dnl From libtool-1.4. Sets the variable with_gnu_ld to yes or no. AC_DEFUN([AC_LIB_PROG_LD_GNU], [AC_CACHE_CHECK([if the linker ($LD) is GNU ld], acl_cv_prog_gnu_ld, [# I'd rather use --version here, but apparently some GNU ld's only accept -v. case `$LD -v 2>&1 conf$$.sh echo "exit 0" >>conf$$.sh chmod +x conf$$.sh if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then PATH_SEPARATOR=';' else PATH_SEPARATOR=: fi rm -f conf$$.sh fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by GCC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]* | [A-Za-z]:[\\/]*)] [re_direlt='/[^/][^/]*/\.\./'] # Canonicalize the path of ld ac_prog=`echo $ac_prog| sed 's%\\\\%/%g'` while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do ac_prog=`echo $ac_prog| sed "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(acl_cv_path_LD, [if test -z "$LD"; then IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}${PATH_SEPARATOR-:}" for ac_dir in $PATH; do test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then acl_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some GNU ld's only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$acl_cv_path_LD" -v 2>&1 < /dev/null` in *GNU* | *'with BFD'*) test "$with_gnu_ld" != no && break ;; *) test "$with_gnu_ld" != yes && break ;; esac fi done IFS="$ac_save_ifs" else acl_cv_path_LD="$LD" # Let the user override the test with a path. fi]) LD="$acl_cv_path_LD" if test -n "$LD"; then AC_MSG_RESULT($LD) else AC_MSG_RESULT(no) fi test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH]) AC_LIB_PROG_LD_GNU ]) dnl @synopsis AC_JNI_INCLUDE_DIR dnl dnl AC_JNI_INCLUDE_DIR finds include directories needed dnl for compiling programs using the JNI interface. dnl dnl JNI include directories are usually in the java distribution dnl This is deduced from the value of JAVAC. When this macro dnl completes, a list of directories is left in the variable dnl JNI_INCLUDE_DIRS. dnl dnl Example usage follows: dnl dnl AC_JNI_INCLUDE_DIR dnl dnl for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS dnl do dnl CPPFLAGS="$CPPFLAGS -I$JNI_INCLUDE_DIR" dnl done dnl dnl If you want to force a specific compiler: dnl dnl - at the configure.in level, set JAVAC=yourcompiler before calling dnl AC_JNI_INCLUDE_DIR dnl dnl - at the configure level, setenv JAVAC dnl dnl Note: This macro can work with the autoconf M4 macros for Java programs. dnl This particular macro is not part of the original set of macros. dnl dnl @author Don Anderson dnl @version $Id: ac_jni_include_dirs.m4,v 1.3 2004/12/24 01:16:37 guidod Exp $ dnl AC_DEFUN([AC_JNI_INCLUDE_DIR],[ JNI_INCLUDE_DIRS="" test "x$JAVAC" = x && AC_MSG_ERROR(['$JAVAC' undefined]) AC_PATH_PROG(_ACJNI_JAVAC, $JAVAC, no) test "x$_ACJNI_JAVAC" = xno && AC_MSG_ERROR([$JAVAC could not be found in path]) _ACJNI_FOLLOW_SYMLINKS("$_ACJNI_JAVAC") _JTOPDIR=`echo "$_ACJNI_FOLLOWED" | sed -e 's://*:/:g' -e 's:/[[^/]]*$::'` case "$host_os" in darwin*) _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'` _JINC="$_JTOPDIR/Headers";; *) _JINC="$_JTOPDIR/include";; esac if test -f "$_JINC/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JINC" else _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'` if test -f "$_JTOPDIR/include/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include" else AC_MSG_ERROR([cannot find java include files]) fi fi # get the likely subdirectories for system specific java includes case "$host_os" in bsdi*) _JNI_INC_SUBDIRS="bsdos";; linux*) _JNI_INC_SUBDIRS="linux genunix";; osf*) _JNI_INC_SUBDIRS="alpha";; solaris*) _JNI_INC_SUBDIRS="solaris";; mingw*) _JNI_INC_SUBDIRS="win32";; cygwin*) _JNI_INC_SUBDIRS="win32";; *) _JNI_INC_SUBDIRS="genunix";; esac # add any subdirectories that are present for JINCSUBDIR in $_JNI_INC_SUBDIRS do if test -d "$_JTOPDIR/include/$JINCSUBDIR"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include/$JINCSUBDIR" fi done ]) # _ACJNI_FOLLOW_SYMLINKS # Follows symbolic links on , # finally setting variable _ACJNI_FOLLOWED # -------------------- AC_DEFUN([_ACJNI_FOLLOW_SYMLINKS],[ # find the include directory relative to the javac executable _cur="$1" while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do AC_MSG_CHECKING(symlink for $_cur) _slink=`ls -ld "$_cur" | sed 's/.* -> //'` case "$_slink" in /*) _cur="$_slink";; # 'X' avoids triggering unwanted echo options. *) _cur=`echo "X$_cur" | sed -e 's/^X//' -e 's:[[^/]]*$::'`"$_slink";; esac AC_MSG_RESULT($_cur) done _ACJNI_FOLLOWED="$_cur" ])# _ACJNI clearsilver-0.10.5/configure0000755001211700116100000072667210645505047012765 00000000000000#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.59. # # Copyright (C) 2003 Free Software Foundation, Inc. # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then set -o posix fi DUALCASE=1; export DUALCASE # for MKS sh # Support unset when possible. if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then as_unset=unset else as_unset=false fi # Work around bugs in pre-3.0 UWIN ksh. $as_unset ENV MAIL MAILPATH PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. for as_var in \ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ LC_TELEPHONE LC_TIME do if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then eval $as_var=C; export $as_var else $as_unset $as_var fi done # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1; then as_expr=expr else as_expr=false fi if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi # Name of the executable. as_me=`$as_basename "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)$' \| \ . : '\(.\)' 2>/dev/null || echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; } /^X\/\(\/\/\)$/{ s//\1/; q; } /^X\/\(\/\).*/{ s//\1/; q; } s/.*/./; q'` # PATH needs CR, and LINENO needs CR and PATH. # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then echo "#! /bin/sh" >conf$$.sh echo "exit 0" >>conf$$.sh chmod +x conf$$.sh if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then PATH_SEPARATOR=';' else PATH_SEPARATOR=: fi rm -f conf$$.sh fi as_lineno_1=$LINENO as_lineno_2=$LINENO as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` test "x$as_lineno_1" != "x$as_lineno_2" && test "x$as_lineno_3" = "x$as_lineno_2" || { # Find who we are. Look in the path if we contain no path at all # relative or not. case $0 in *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2 { (exit 1); exit 1; }; } fi case $CONFIG_SHELL in '') as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for as_base in sh bash ksh sh5; do case $as_dir in /*) if ("$as_dir/$as_base" -c ' as_lineno_1=$LINENO as_lineno_2=$LINENO as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` test "x$as_lineno_1" != "x$as_lineno_2" && test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; } $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; } CONFIG_SHELL=$as_dir/$as_base export CONFIG_SHELL exec "$CONFIG_SHELL" "$0" ${1+"$@"} fi;; esac done done ;; esac # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a # line-number line before each line; the second 'sed' does the real # work. The second script uses 'N' to pair each line-number line # with the numbered line, and appends trailing '-' during # substitution so that $LINENO is not a special case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-) sed '=' <$as_myself | sed ' N s,$,-, : loop s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3, t loop s,-$,, s,^['$as_cr_digits']*\n,, ' >$as_me.lineno && chmod +x $as_me.lineno || { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensible to this). . ./$as_me.lineno # Exit status is that of the last command. exit } case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in *c*,-n*) ECHO_N= ECHO_C=' ' ECHO_T=' ' ;; *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; *) ECHO_N= ECHO_C='\c' ECHO_T= ;; esac if expr a : '\(a\)' >/dev/null 2>&1; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file echo >conf$$.file if ln -s conf$$.file conf$$ 2>/dev/null; then # We could just check for DJGPP; but this test a) works b) is more generic # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04). if test -f conf$$.exe; then # Don't use ln at all; we don't have any links as_ln_s='cp -p' else as_ln_s='ln -s' fi elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.file if mkdir -p . 2>/dev/null; then as_mkdir_p=: else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_executable_p="test -f" # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" # IFS # We need space, tab and new line, in precisely that order. as_nl=' ' IFS=" $as_nl" # CDPATH. $as_unset CDPATH # Name of the host. # hostname on some systems (SVR3.2, Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` exec 6>&1 # # Initializations. # ac_default_prefix=/usr/local ac_config_libobj_dir=. cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= SHELL=${CONFIG_SHELL-/bin/sh} # Maximum number of lines to put in a shell here document. # This variable seems obsolete. It should probably be removed, and # only ac_max_sed_lines should be used. : ${ac_max_here_lines=38} # Identity of this package. PACKAGE_NAME= PACKAGE_TARNAME= PACKAGE_VERSION= PACKAGE_STRING= PACKAGE_BUGREPORT= ac_unique_file="cgi/cgi.c" # Factoring default headers for most tests. ac_includes_default="\ #include #if HAVE_SYS_TYPES_H # include #endif #if HAVE_SYS_STAT_H # include #endif #if STDC_HEADERS # include # include #else # if HAVE_STDLIB_H # include # endif #endif #if HAVE_STRING_H # if !STDC_HEADERS && HAVE_MEMORY_H # include # endif # include #endif #if HAVE_STRINGS_H # include #endif #if HAVE_INTTYPES_H # include #else # if HAVE_STDINT_H # include # endif #endif #if HAVE_UNISTD_H # include #endif" ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT CPP LN_S AR RANLIB ac_ct_RANLIB SET_MAKE INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA EGREP build build_cpu build_vendor build_os host host_cpu host_vendor host_os _ACJNI_JAVAC USE_MINGW32 APXS_PATH PERL RUBY BUILD_WRAPPERS JAVA_PATH JAVA_INCLUDE_PATH PYTHON PYTHON_INC PYTHON_LIB PYTHON_SITE EXTRA_UTL_SRC EXTRA_UTL_OBJS CSHARP_PATH LIBOBJS LTLIBOBJS' ac_subst_files='' # Initialize some variables set by options. ac_init_help= ac_init_version=false # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datadir='${prefix}/share' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' libdir='${exec_prefix}/lib' includedir='${prefix}/include' oldincludedir='/usr/include' infodir='${prefix}/info' mandir='${prefix}/man' ac_prev= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval "$ac_prev=\$ac_option" ac_prev= continue fi ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'` # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_option in -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad | --data | --dat | --da) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \ | --da=*) datadir=$ac_optarg ;; -disable-* | --disable-*) ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid feature name: $ac_feature" >&2 { (exit 1); exit 1; }; } ac_feature=`echo $ac_feature | sed 's/-/_/g'` eval "enable_$ac_feature=no" ;; -enable-* | --enable-*) ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid feature name: $ac_feature" >&2 { (exit 1); exit 1; }; } ac_feature=`echo $ac_feature | sed 's/-/_/g'` case $ac_option in *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;; *) ac_optarg=yes ;; esac eval "enable_$ac_feature='$ac_optarg'" ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst \ | --locals | --local | --loca | --loc | --lo) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* \ | --locals=* | --local=* | --loca=* | --loc=* | --lo=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid package name: $ac_package" >&2 { (exit 1); exit 1; }; } ac_package=`echo $ac_package| sed 's/-/_/g'` case $ac_option in *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;; *) ac_optarg=yes ;; esac eval "with_$ac_package='$ac_optarg'" ;; -without-* | --without-*) ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid package name: $ac_package" >&2 { (exit 1); exit 1; }; } ac_package=`echo $ac_package | sed 's/-/_/g'` eval "with_$ac_package=no" ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) { echo "$as_me: error: unrecognized option: $ac_option Try \`$0 --help' for more information." >&2 { (exit 1); exit 1; }; } ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 { (exit 1); exit 1; }; } ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` eval "$ac_envvar='$ac_optarg'" export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` { echo "$as_me: error: missing argument to $ac_option" >&2 { (exit 1); exit 1; }; } fi # Be sure to have absolute paths. for ac_var in exec_prefix prefix do eval ac_val=$`echo $ac_var` case $ac_val in [\\/$]* | ?:[\\/]* | NONE | '' ) ;; *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 { (exit 1); exit 1; }; };; esac done # Be sure to have absolute paths. for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \ localstatedir libdir includedir oldincludedir infodir mandir do eval ac_val=$`echo $ac_var` case $ac_val in [\\/$]* | ?:[\\/]* ) ;; *) { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 { (exit 1); exit 1; }; };; esac done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then its parent. ac_confdir=`(dirname "$0") 2>/dev/null || $as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$0" : 'X\(//\)[^/]' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| \ . : '\(.\)' 2>/dev/null || echo X"$0" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } /^X\(\/\/\)[^/].*/{ s//\1/; q; } /^X\(\/\/\)$/{ s//\1/; q; } /^X\(\/\).*/{ s//\1/; q; } s/.*/./; q'` srcdir=$ac_confdir if test ! -r $srcdir/$ac_unique_file; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r $srcdir/$ac_unique_file; then if test "$ac_srcdir_defaulted" = yes; then { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2 { (exit 1); exit 1; }; } else { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 { (exit 1); exit 1; }; } fi fi (cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null || { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2 { (exit 1); exit 1; }; } srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'` ac_env_build_alias_set=${build_alias+set} ac_env_build_alias_value=$build_alias ac_cv_env_build_alias_set=${build_alias+set} ac_cv_env_build_alias_value=$build_alias ac_env_host_alias_set=${host_alias+set} ac_env_host_alias_value=$host_alias ac_cv_env_host_alias_set=${host_alias+set} ac_cv_env_host_alias_value=$host_alias ac_env_target_alias_set=${target_alias+set} ac_env_target_alias_value=$target_alias ac_cv_env_target_alias_set=${target_alias+set} ac_cv_env_target_alias_value=$target_alias ac_env_CC_set=${CC+set} ac_env_CC_value=$CC ac_cv_env_CC_set=${CC+set} ac_cv_env_CC_value=$CC ac_env_CFLAGS_set=${CFLAGS+set} ac_env_CFLAGS_value=$CFLAGS ac_cv_env_CFLAGS_set=${CFLAGS+set} ac_cv_env_CFLAGS_value=$CFLAGS ac_env_LDFLAGS_set=${LDFLAGS+set} ac_env_LDFLAGS_value=$LDFLAGS ac_cv_env_LDFLAGS_set=${LDFLAGS+set} ac_cv_env_LDFLAGS_value=$LDFLAGS ac_env_CPPFLAGS_set=${CPPFLAGS+set} ac_env_CPPFLAGS_value=$CPPFLAGS ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set} ac_cv_env_CPPFLAGS_value=$CPPFLAGS ac_env_CPP_set=${CPP+set} ac_env_CPP_value=$CPP ac_cv_env_CPP_set=${CPP+set} ac_cv_env_CPP_value=$CPP # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures this package to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] _ACEOF cat <<_ACEOF Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --datadir=DIR read-only architecture-independent data [PREFIX/share] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --infodir=DIR info documentation [PREFIX/info] --mandir=DIR man documentation [PREFIX/man] _ACEOF cat <<\_ACEOF System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then cat <<\_ACEOF Optional Features: --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-wdb Disables building of wdb --disable-compression Disables HTML Compression support --enable-remote-debugger Enables remote X CGI debugging --disable-apache Disables building of apache 1.3.x module --disable-python Disables building of python module --disable-perl Disables building of perl module --disable-ruby Disables building of ruby module --disable-java Disables building of java module --disable-csharp Disables building of csharp module --enable-gettext Enables gettext message translation Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-apache=path Set location of Apache installation --with-python=path Set location of Python Interpreter --with-perl=path Set location of Perl binary --with-ruby=path Set location of Ruby binary --with-java=path Set location of J2SDK --with-csharp=path Set location of csharp Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory CPPFLAGS C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. _ACEOF fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. ac_popdir=`pwd` for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d $ac_dir || continue ac_builddir=. if test "$ac_dir" != .; then ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` # A "../" for each directory in $ac_dir_suffix. ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` else ac_dir_suffix= ac_top_builddir= fi case $srcdir in .) # No --srcdir option. We are building in place. ac_srcdir=. if test -z "$ac_top_builddir"; then ac_top_srcdir=. else ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` fi ;; [\\/]* | ?:[\\/]* ) # Absolute path. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ;; *) # Relative path. ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_builddir$srcdir ;; esac # Do not use `cd foo && pwd` to compute absolute paths, because # the directories may not exist. case `pwd` in .) ac_abs_builddir="$ac_dir";; *) case "$ac_dir" in .) ac_abs_builddir=`pwd`;; [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; *) ac_abs_builddir=`pwd`/"$ac_dir";; esac;; esac case $ac_abs_builddir in .) ac_abs_top_builddir=${ac_top_builddir}.;; *) case ${ac_top_builddir}. in .) ac_abs_top_builddir=$ac_abs_builddir;; [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; esac;; esac case $ac_abs_builddir in .) ac_abs_srcdir=$ac_srcdir;; *) case $ac_srcdir in .) ac_abs_srcdir=$ac_abs_builddir;; [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; esac;; esac case $ac_abs_builddir in .) ac_abs_top_srcdir=$ac_top_srcdir;; *) case $ac_top_srcdir in .) ac_abs_top_srcdir=$ac_abs_builddir;; [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; esac;; esac cd $ac_dir # Check for guested configure; otherwise get Cygnus style configure. if test -f $ac_srcdir/configure.gnu; then echo $SHELL $ac_srcdir/configure.gnu --help=recursive elif test -f $ac_srcdir/configure; then echo $SHELL $ac_srcdir/configure --help=recursive elif test -f $ac_srcdir/configure.ac || test -f $ac_srcdir/configure.in; then echo $ac_configure --help else echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi cd "$ac_popdir" done fi test -n "$ac_init_help" && exit 0 if $ac_init_version; then cat <<\_ACEOF Copyright (C) 2003 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit 0 fi exec 5>config.log cat >&5 <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by $as_me, which was generated by GNU Autoconf 2.59. Invocation command line was $ $0 $@ _ACEOF { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` hostinfo = `(hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. echo "PATH: $as_dir" done } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_sep= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; 2) ac_configure_args1="$ac_configure_args1 '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'" # Get rid of the leading space. ac_sep=" " ;; esac done done $as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } $as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Be sure not to use single quotes in there, as some shells, # such as our DU 5.0 friend, will then `close' the trap. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo cat <<\_ASBOX ## ---------------- ## ## Cache variables. ## ## ---------------- ## _ASBOX echo # The following way of writing the cache mishandles newlines in values, { (set) 2>&1 | case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in *ac_space=\ *) sed -n \ "s/'"'"'/'"'"'\\\\'"'"''"'"'/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p" ;; *) sed -n \ "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p" ;; esac; } echo cat <<\_ASBOX ## ----------------- ## ## Output variables. ## ## ----------------- ## _ASBOX echo for ac_var in $ac_subst_vars do eval ac_val=$`echo $ac_var` echo "$ac_var='"'"'$ac_val'"'"'" done | sort echo if test -n "$ac_subst_files"; then cat <<\_ASBOX ## ------------- ## ## Output files. ## ## ------------- ## _ASBOX echo for ac_var in $ac_subst_files do eval ac_val=$`echo $ac_var` echo "$ac_var='"'"'$ac_val'"'"'" done | sort echo fi if test -s confdefs.h; then cat <<\_ASBOX ## ----------- ## ## confdefs.h. ## ## ----------- ## _ASBOX echo sed "/^$/d" confdefs.h | sort echo fi test "$ac_signal" != 0 && echo "$as_me: caught signal $ac_signal" echo "$as_me: exit $exit_status" } >&5 rm -f core *.core && rm -rf conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -rf conftest* confdefs.h # AIX cpp loses on an empty file, so make sure it contains at least a newline. echo >confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer explicitly selected file to automatically selected ones. if test -z "$CONFIG_SITE"; then if test "x$prefix" != xNONE; then CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site" else CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" fi fi for ac_site_file in $CONFIG_SITE; do if test -r "$ac_site_file"; then { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special # files actually), so we avoid doing that. if test -f "$cache_file"; then { echo "$as_me:$LINENO: loading cache $cache_file" >&5 echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . $cache_file;; *) . ./$cache_file;; esac fi else { echo "$as_me:$LINENO: creating cache $cache_file" >&5 echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in `(set) 2>&1 | sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val="\$ac_cv_env_${ac_var}_value" eval ac_new_val="\$ac_env_${ac_var}_value" case $ac_old_set,$ac_new_set in set,) { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 echo "$as_me: former value: $ac_old_val" >&2;} { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 echo "$as_me: current value: $ac_new_val" >&2;} ac_cache_corrupted=: fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *" "*|*" "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 echo "$as_me: error: changes in the environment can compromise the build" >&2;} { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} { (exit 1); exit 1; }; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers cs_config.h" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then echo "$as_me:$LINENO: result: $CC" >&5 echo "${ECHO_T}$CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 echo "${ECHO_T}$ac_ct_CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi CC=$ac_ct_CC else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then echo "$as_me:$LINENO: result: $CC" >&5 echo "${ECHO_T}$CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="cc" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 echo "${ECHO_T}$ac_ct_CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi CC=$ac_ct_CC else CC="$ac_cv_prog_CC" fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then echo "$as_me:$LINENO: result: $CC" >&5 echo "${ECHO_T}$CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then echo "$as_me:$LINENO: result: $CC" >&5 echo "${ECHO_T}$CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 echo "${ECHO_T}$ac_ct_CC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi test -n "$ac_ct_CC" && break done CC=$ac_ct_CC fi fi test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&5 echo "$as_me: error: no acceptable C compiler found in \$PATH See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; } # Provide some information about the compiler. echo "$as_me:$LINENO:" \ "checking for C compiler version" >&5 ac_compiler=`set X $ac_compile; echo $2` { (eval echo "$as_me:$LINENO: \"$ac_compiler --version &5\"") >&5 (eval $ac_compiler --version &5) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (eval echo "$as_me:$LINENO: \"$ac_compiler -v &5\"") >&5 (eval $ac_compiler -v &5) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } { (eval echo "$as_me:$LINENO: \"$ac_compiler -V &5\"") >&5 (eval $ac_compiler -V &5) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6 ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5 (eval $ac_link_default) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # Find the output, starting from the most likely. This scheme is # not robust to junk in `.', hence go to wildcards (a.*) only as a last # resort. # Be careful to initialize this variable, since it used to be cached. # Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile. ac_cv_exeext= # b.out is created by i960 compilers. for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;; conftest.$ac_ext ) # This is the source file. ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` # FIXME: I believe we export ac_cv_exeext for Libtool, # but it would be cool to find out if it's true. Does anybody # maintain Libtool? --akim. export ac_cv_exeext break;; * ) break;; esac done else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { echo "$as_me:$LINENO: error: C compiler cannot create executables See \`config.log' for more details." >&5 echo "$as_me: error: C compiler cannot create executables See \`config.log' for more details." >&2;} { (exit 77); exit 77; }; } fi ac_exeext=$ac_cv_exeext echo "$as_me:$LINENO: result: $ac_file" >&5 echo "${ECHO_T}$ac_file" >&6 # Check the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. echo "$as_me:$LINENO: checking whether the C compiler works" >&5 echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6 # FIXME: These cross compiler hacks should be removed for Autoconf 3.0 # If not cross compiling, check that we can run a simple program. if test "$cross_compiling" != yes; then if { ac_try='./$ac_file' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { echo "$as_me:$LINENO: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&5 echo "$as_me: error: cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; } fi fi fi echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 rm -f a.out a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save # Check the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6 echo "$as_me:$LINENO: result: $cross_compiling" >&5 echo "${ECHO_T}$cross_compiling" >&6 echo "$as_me:$LINENO: checking for suffix of executables" >&5 echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6 if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` export ac_cv_exeext break;; * ) break;; esac done else { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&5 echo "$as_me: error: cannot compute suffix of executables: cannot compile and link See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; } fi rm -f conftest$ac_cv_exeext echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 echo "${ECHO_T}$ac_cv_exeext" >&6 rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT echo "$as_me:$LINENO: checking for suffix of object files" >&5 echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6 if test "${ac_cv_objext+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; then for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&5 echo "$as_me: error: cannot compute suffix of object files: cannot compile See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 echo "${ECHO_T}$ac_cv_objext" >&6 OBJEXT=$ac_cv_objext ac_objext=$OBJEXT echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6 if test "${ac_cv_c_compiler_gnu+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_compiler_gnu=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_compiler_gnu=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6 GCC=`test $ac_compiler_gnu = yes && echo yes` ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS CFLAGS="-g" echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6 if test "${ac_cv_prog_cc_g+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_prog_cc_g=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_prog_cc_g=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 echo "${ECHO_T}$ac_cv_prog_cc_g" >&6 if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5 echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6 if test "${ac_cv_prog_cc_stdc+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_cv_prog_cc_stdc=no ac_save_CC=$CC cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include #include /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std1 is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std1. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF # Don't try gcc -ansi; that turns off useful extensions and # breaks some systems' header files. # AIX -qlanglvl=ansi # Ultrix and OSF/1 -std1 # HP-UX 10.20 and later -Ae # HP-UX older versions -Aa -D_HPUX_SOURCE # SVR4 -Xc -D__EXTENSIONS__ for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_prog_cc_stdc=$ac_arg break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext done rm -f conftest.$ac_ext conftest.$ac_objext CC=$ac_save_CC fi case "x$ac_cv_prog_cc_stdc" in x|xno) echo "$as_me:$LINENO: result: none needed" >&5 echo "${ECHO_T}none needed" >&6 ;; *) echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5 echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6 CC="$CC $ac_cv_prog_cc_stdc" ;; esac # Some people use a C++ compiler to compile C. Since we use `exit', # in C++ we need to declare it. In case someone uses the same compiler # for both compiling C and C++ we need to have the C++ compiler decide # the declaration of exit, since it's the most demanding environment. cat >conftest.$ac_ext <<_ACEOF #ifndef __cplusplus choke me #endif _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then for ac_declaration in \ '' \ 'extern "C" void std::exit (int) throw (); using std::exit;' \ 'extern "C" void std::exit (int); using std::exit;' \ 'extern "C" void exit (int) throw ();' \ 'extern "C" void exit (int);' \ 'void exit (int);' do cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_declaration #include int main () { exit (42); ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then : else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 continue fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_declaration int main () { exit (42); ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext done rm -f conftest* if test -n "$ac_declaration"; then echo '#ifdef __cplusplus' >>confdefs.h echo $ac_declaration >>confdefs.h echo '#endif' >>confdefs.h fi else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6 # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if test "${ac_cv_prog_CPP+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then : else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. continue fi rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether non-existent headers # can be detected and how. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then # Broken: success on invalid input. continue else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext if $ac_preproc_ok; then break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi echo "$as_me:$LINENO: result: $CPP" >&5 echo "${ECHO_T}$CPP" >&6 ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then : else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Broken: fails on valid input. continue fi rm -f conftest.err conftest.$ac_ext # OK, works on sane cases. Now check whether non-existent headers # can be detected and how. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then # Broken: success on invalid input. continue else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&5 echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details." >&2;} { (exit 1); exit 1; }; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu echo "$as_me:$LINENO: checking whether ln -s works" >&5 echo $ECHO_N "checking whether ln -s works... $ECHO_C" >&6 LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else echo "$as_me:$LINENO: result: no, using $LN_S" >&5 echo "${ECHO_T}no, using $LN_S" >&6 fi for ac_prog in ar aal do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_AR+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_prog" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then echo "$as_me:$LINENO: result: $AR" >&5 echo "${ECHO_T}$AR" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi test -n "$AR" && break done test -n "$AR" || AR="ar" if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_RANLIB+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then echo "$as_me:$LINENO: result: $RANLIB" >&5 echo "${ECHO_T}$RANLIB" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done test -z "$ac_cv_prog_ac_ct_RANLIB" && ac_cv_prog_ac_ct_RANLIB=":" fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5 echo "${ECHO_T}$ac_ct_RANLIB" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi RANLIB=$ac_ct_RANLIB else RANLIB="$ac_cv_prog_RANLIB" fi echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6 set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y,:./+-,___p_,'` if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.make <<\_ACEOF all: @echo 'ac_maketemp="$(MAKE)"' _ACEOF # GNU make sometimes prints "make[1]: Entering...", which would confuse us. eval `${MAKE-make} -f conftest.make 2>/dev/null | grep temp=` if test -n "$ac_maketemp"; then eval ac_cv_prog_make_${ac_make}_set=yes else eval ac_cv_prog_make_${ac_make}_set=no fi rm -f conftest.make fi if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 SET_MAKE= else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 SET_MAKE="MAKE=${MAKE-make}" fi ac_aux_dir= for ac_dir in $srcdir $srcdir/.. $srcdir/../..; do if test -f $ac_dir/install-sh; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f $ac_dir/install.sh; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f $ac_dir/shtool; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&5 echo "$as_me: error: cannot find install-sh or install.sh in $srcdir $srcdir/.. $srcdir/../.." >&2;} { (exit 1); exit 1; }; } fi ac_config_guess="$SHELL $ac_aux_dir/config.guess" ac_config_sub="$SHELL $ac_aux_dir/config.sub" ac_configure="$SHELL $ac_aux_dir/configure" # This should be Cygnus configure. # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6 if test -z "$INSTALL"; then if test "${ac_cv_path_install+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in ./ | .// | /cC/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi done done ;; esac done fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. We don't cache a # path for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the path is relative. INSTALL=$ac_install_sh fi fi echo "$as_me:$LINENO: result: $INSTALL" >&5 echo "${ECHO_T}$INSTALL" >&6 # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' echo "$as_me:$LINENO: checking for Neotonic Paths" >&5 echo $ECHO_N "checking for Neotonic Paths... $ECHO_C" >&6 if test -d /neo/opt/include; then echo "$as_me:$LINENO: result: found" >&5 echo "${ECHO_T}found" >&6 CPPFLAGS="$CPPFLAGS -I/neo/opt/include" LDFLAGS="$LDFLAGS -L/neo/opt/lib" else echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 fi ac_header_dirent=no for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6 if eval "test \"\${$as_ac_Header+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include <$ac_hdr> int main () { if ((DIR *) 0) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_Header=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 if test `eval echo '${'$as_ac_Header'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF ac_header_dirent=$ac_hdr; break fi done # Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. if test $ac_header_dirent = dirent.h; then echo "$as_me:$LINENO: checking for library containing opendir" >&5 echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6 if test "${ac_cv_search_opendir+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_func_search_save_LIBS=$LIBS ac_cv_search_opendir=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char opendir (); int main () { opendir (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_search_opendir="none required" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_search_opendir" = no; then for ac_lib in dir; do LIBS="-l$ac_lib $ac_func_search_save_LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char opendir (); int main () { opendir (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_search_opendir="-l$ac_lib" break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext done fi LIBS=$ac_func_search_save_LIBS fi echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 echo "${ECHO_T}$ac_cv_search_opendir" >&6 if test "$ac_cv_search_opendir" != no; then test "$ac_cv_search_opendir" = "none required" || LIBS="$ac_cv_search_opendir $LIBS" fi else echo "$as_me:$LINENO: checking for library containing opendir" >&5 echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6 if test "${ac_cv_search_opendir+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_func_search_save_LIBS=$LIBS ac_cv_search_opendir=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char opendir (); int main () { opendir (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_search_opendir="none required" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_search_opendir" = no; then for ac_lib in x; do LIBS="-l$ac_lib $ac_func_search_save_LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char opendir (); int main () { opendir (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_search_opendir="-l$ac_lib" break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext done fi LIBS=$ac_func_search_save_LIBS fi echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 echo "${ECHO_T}$ac_cv_search_opendir" >&6 if test "$ac_cv_search_opendir" != no; then test "$ac_cv_search_opendir" = "none required" || LIBS="$ac_cv_search_opendir $LIBS" fi fi echo "$as_me:$LINENO: checking for egrep" >&5 echo $ECHO_N "checking for egrep... $ECHO_C" >&6 if test "${ac_cv_prog_egrep+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if echo a | (grep -E '(a|b)') >/dev/null 2>&1 then ac_cv_prog_egrep='grep -E' else ac_cv_prog_egrep='egrep' fi fi echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5 echo "${ECHO_T}$ac_cv_prog_egrep" >&6 EGREP=$ac_cv_prog_egrep echo "$as_me:$LINENO: checking for ANSI C header files" >&5 echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6 if test "${ac_cv_header_stdc+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_header_stdc=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_stdc=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) exit(2); exit (0); } _ACEOF rm -f conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then : else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_header_stdc=no fi rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi fi echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 echo "${ECHO_T}$ac_cv_header_stdc" >&6 if test $ac_cv_header_stdc = yes; then cat >>confdefs.h <<\_ACEOF #define STDC_HEADERS 1 _ACEOF fi echo "$as_me:$LINENO: checking for sys/wait.h that is POSIX.1 compatible" >&5 echo $ECHO_N "checking for sys/wait.h that is POSIX.1 compatible... $ECHO_C" >&6 if test "${ac_cv_header_sys_wait_h+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #ifndef WIFEXITED # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif int main () { int s; wait (&s); s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_header_sys_wait_h=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_sys_wait_h=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_header_sys_wait_h" >&5 echo "${ECHO_T}$ac_cv_header_sys_wait_h" >&6 if test $ac_cv_header_sys_wait_h = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_SYS_WAIT_H 1 _ACEOF fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_header" >&5 echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 if eval "test \"\${$as_ac_Header+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include <$ac_header> _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_Header=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_Header=no" fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 if test `eval echo '${'$as_ac_Header'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_header in fcntl.h stdarg.h varargs.h limits.h strings.h sys/ioctl.h sys/time.h unistd.h features.h do as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` if eval "test \"\${$as_ac_Header+set}\" = set"; then echo "$as_me:$LINENO: checking for $ac_header" >&5 echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 if eval "test \"\${$as_ac_Header+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 else # Is the header compilable? echo "$as_me:$LINENO: checking $ac_header usability" >&5 echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include <$ac_header> _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_header_compiler=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 echo "${ECHO_T}$ac_header_compiler" >&6 # Is the header present? echo "$as_me:$LINENO: checking $ac_header presence" >&5 echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include <$ac_header> _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then ac_header_preproc=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 echo "${ECHO_T}$ac_header_preproc" >&6 # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------ ## ## Report this to the AC_PACKAGE_NAME lists. ## ## ------------------------------------------ ## _ASBOX ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac echo "$as_me:$LINENO: checking for $ac_header" >&5 echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6 if eval "test \"\${$as_ac_Header+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else eval "$as_ac_Header=\$ac_header_preproc" fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6 fi if test `eval echo '${'$as_ac_Header'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6 if test "${ac_cv_c_const+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ int main () { /* FIXME: Include the comments suggested by Paul. */ #ifndef __cplusplus /* Ultrix mips cc rejects this. */ typedef int charset[2]; const charset x; /* SunOS 4.1.1 cc rejects this. */ char const *const *ccp; char **p; /* NEC SVR4.0.2 mips cc rejects this. */ struct point {int x, y;}; static struct point const zero = {0,0}; /* AIX XL C 1.02.0.0 rejects this. It does not let you subtract one const X* pointer from another in an arm of an if-expression whose if-part is not a constant expression */ const char *g = "string"; ccp = &g + (g ? g-g : 0); /* HPUX 7.0 cc rejects these. */ ++ccp; p = (char**) ccp; ccp = (char const *const *) p; { /* SCO 3.2v4 cc rejects this. */ char *t; char const *s = 0 ? (char *) 0 : (char const *) 0; *t++ = 0; } { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ int x[] = {25, 17}; const int *foo = &x[0]; ++foo; } { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ typedef const int *iptr; iptr p = 0; ++p; } { /* AIX XL C 1.02.0.0 rejects this saying "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ struct s { int j; const int *ap[3]; }; struct s *b; b->j = 5; } { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ const int foo = 10; } #endif ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_c_const=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_c_const=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 echo "${ECHO_T}$ac_cv_c_const" >&6 if test $ac_cv_c_const = no; then cat >>confdefs.h <<\_ACEOF #define const _ACEOF fi echo "$as_me:$LINENO: checking for mode_t" >&5 echo $ECHO_N "checking for mode_t... $ECHO_C" >&6 if test "${ac_cv_type_mode_t+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default int main () { if ((mode_t *) 0) return 0; if (sizeof (mode_t)) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_type_mode_t=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_mode_t=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_type_mode_t" >&5 echo "${ECHO_T}$ac_cv_type_mode_t" >&6 if test $ac_cv_type_mode_t = yes; then : else cat >>confdefs.h <<_ACEOF #define mode_t int _ACEOF fi echo "$as_me:$LINENO: checking for off_t" >&5 echo $ECHO_N "checking for off_t... $ECHO_C" >&6 if test "${ac_cv_type_off_t+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default int main () { if ((off_t *) 0) return 0; if (sizeof (off_t)) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_type_off_t=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_off_t=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_type_off_t" >&5 echo "${ECHO_T}$ac_cv_type_off_t" >&6 if test $ac_cv_type_off_t = yes; then : else cat >>confdefs.h <<_ACEOF #define off_t long _ACEOF fi echo "$as_me:$LINENO: checking for pid_t" >&5 echo $ECHO_N "checking for pid_t... $ECHO_C" >&6 if test "${ac_cv_type_pid_t+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default int main () { if ((pid_t *) 0) return 0; if (sizeof (pid_t)) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_type_pid_t=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_pid_t=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 echo "${ECHO_T}$ac_cv_type_pid_t" >&6 if test $ac_cv_type_pid_t = yes; then : else cat >>confdefs.h <<_ACEOF #define pid_t int _ACEOF fi echo "$as_me:$LINENO: checking for size_t" >&5 echo $ECHO_N "checking for size_t... $ECHO_C" >&6 if test "${ac_cv_type_size_t+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default int main () { if ((size_t *) 0) return 0; if (sizeof (size_t)) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_type_size_t=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_size_t=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_type_size_t" >&5 echo "${ECHO_T}$ac_cv_type_size_t" >&6 if test $ac_cv_type_size_t = yes; then : else cat >>confdefs.h <<_ACEOF #define size_t unsigned _ACEOF fi echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5 echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6 if test "${ac_cv_header_time+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include int main () { if ((struct tm *) 0) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_header_time=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_header_time=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5 echo "${ECHO_T}$ac_cv_header_time" >&6 if test $ac_cv_header_time = yes; then cat >>confdefs.h <<\_ACEOF #define TIME_WITH_SYS_TIME 1 _ACEOF fi echo "$as_me:$LINENO: checking whether struct tm is in sys/time.h or time.h" >&5 echo $ECHO_N "checking whether struct tm is in sys/time.h or time.h... $ECHO_C" >&6 if test "${ac_cv_struct_tm+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include int main () { struct tm *tp; tp->tm_sec; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_struct_tm=time.h else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_struct_tm=sys/time.h fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_struct_tm" >&5 echo "${ECHO_T}$ac_cv_struct_tm" >&6 if test $ac_cv_struct_tm = sys/time.h; then cat >>confdefs.h <<\_ACEOF #define TM_IN_SYS_TIME 1 _ACEOF fi echo "$as_me:$LINENO: checking for struct tm.tm_zone" >&5 echo $ECHO_N "checking for struct tm.tm_zone... $ECHO_C" >&6 if test "${ac_cv_member_struct_tm_tm_zone+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include <$ac_cv_struct_tm> int main () { static struct tm ac_aggr; if (ac_aggr.tm_zone) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_member_struct_tm_tm_zone=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include <$ac_cv_struct_tm> int main () { static struct tm ac_aggr; if (sizeof ac_aggr.tm_zone) return 0; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_member_struct_tm_tm_zone=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_member_struct_tm_tm_zone=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_member_struct_tm_tm_zone" >&5 echo "${ECHO_T}$ac_cv_member_struct_tm_tm_zone" >&6 if test $ac_cv_member_struct_tm_tm_zone = yes; then cat >>confdefs.h <<_ACEOF #define HAVE_STRUCT_TM_TM_ZONE 1 _ACEOF fi if test "$ac_cv_member_struct_tm_tm_zone" = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_TM_ZONE 1 _ACEOF else echo "$as_me:$LINENO: checking for tzname" >&5 echo $ECHO_N "checking for tzname... $ECHO_C" >&6 if test "${ac_cv_var_tzname+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #ifndef tzname /* For SGI. */ extern char *tzname[]; /* RS6000 and others reject char **tzname. */ #endif int main () { atoi(*tzname); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_var_tzname=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_var_tzname=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_var_tzname" >&5 echo "${ECHO_T}$ac_cv_var_tzname" >&6 if test $ac_cv_var_tzname = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_TZNAME 1 _ACEOF fi fi echo "$as_me:$LINENO: checking return type of signal handlers" >&5 echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6 if test "${ac_cv_type_signal+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #ifdef signal # undef signal #endif #ifdef __cplusplus extern "C" void (*signal (int, void (*)(int)))(int); #else void (*signal ()) (); #endif int main () { int i; ; return 0; } _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_type_signal=void else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_type_signal=int fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 echo "${ECHO_T}$ac_cv_type_signal" >&6 cat >>confdefs.h <<_ACEOF #define RETSIGTYPE $ac_cv_type_signal _ACEOF for ac_func in strftime do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF else # strftime is in -lintl on SCO UNIX. echo "$as_me:$LINENO: checking for strftime in -lintl" >&5 echo $ECHO_N "checking for strftime in -lintl... $ECHO_C" >&6 if test "${ac_cv_lib_intl_strftime+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lintl $LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char strftime (); int main () { strftime (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_lib_intl_strftime=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_intl_strftime=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi echo "$as_me:$LINENO: result: $ac_cv_lib_intl_strftime" >&5 echo "${ECHO_T}$ac_cv_lib_intl_strftime" >&6 if test $ac_cv_lib_intl_strftime = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_STRFTIME 1 _ACEOF LIBS="-lintl $LIBS" fi fi done for ac_func in vprintf do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF echo "$as_me:$LINENO: checking for _doprnt" >&5 echo $ECHO_N "checking for _doprnt... $ECHO_C" >&6 if test "${ac_cv_func__doprnt+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define _doprnt to an innocuous variant, in case declares _doprnt. For example, HP-UX 11i declares gettimeofday. */ #define _doprnt innocuous__doprnt /* System header to define __stub macros and hopefully few prototypes, which can conflict with char _doprnt (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef _doprnt /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char _doprnt (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub__doprnt) || defined (__stub____doprnt) choke me #else char (*f) () = _doprnt; #endif #ifdef __cplusplus } #endif int main () { return f != _doprnt; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func__doprnt=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func__doprnt=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func__doprnt" >&5 echo "${ECHO_T}$ac_cv_func__doprnt" >&6 if test $ac_cv_func__doprnt = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_DOPRNT 1 _ACEOF fi fi done echo "$as_me:$LINENO: checking for wait3 that fills in rusage" >&5 echo $ECHO_N "checking for wait3 that fills in rusage... $ECHO_C" >&6 if test "${ac_cv_func_wait3_rusage+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else if test "$cross_compiling" = yes; then ac_cv_func_wait3_rusage=no else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include #include #include #include /* HP-UX has wait3 but does not fill in rusage at all. */ int main () { struct rusage r; int i; /* Use a field that we can force nonzero -- voluntary context switches. For systems like NeXT and OSF/1 that don't set it, also use the system CPU time. And page faults (I/O) for Linux. */ r.ru_nvcsw = 0; r.ru_stime.tv_sec = 0; r.ru_stime.tv_usec = 0; r.ru_majflt = r.ru_minflt = 0; switch (fork ()) { case 0: /* Child. */ sleep(1); /* Give up the CPU. */ _exit(0); break; case -1: /* What can we do? */ _exit(0); break; default: /* Parent. */ wait3(&i, 0, &r); /* Avoid "text file busy" from rm on fast HP-UX machines. */ sleep(2); exit (r.ru_nvcsw == 0 && r.ru_majflt == 0 && r.ru_minflt == 0 && r.ru_stime.tv_sec == 0 && r.ru_stime.tv_usec == 0); } } _ACEOF rm -f conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='./conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_wait3_rusage=yes else echo "$as_me: program exited with status $ac_status" >&5 echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ( exit $ac_status ) ac_cv_func_wait3_rusage=no fi rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext fi fi echo "$as_me:$LINENO: result: $ac_cv_func_wait3_rusage" >&5 echo "${ECHO_T}$ac_cv_func_wait3_rusage" >&6 if test $ac_cv_func_wait3_rusage = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_WAIT3 1 _ACEOF fi for ac_func in gettimeofday mktime putenv strerror strspn strtod strtol strtoul do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done for ac_func in random rand drand48 do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF fi done EXTRA_UTL_OBJS= EXTRA_UTL_SRC= cs_cv_wdb=no # Check whether --enable-apache or --disable-apache was given. if test "${enable_apache+set}" = set; then enableval="$enable_apache" if test $enableval = no; then echo "$as_me:$LINENO: result: Disabling wdb code" >&5 echo "${ECHO_T}Disabling wdb code" >&6 else echo "$as_me:$LINENO: checking for library containing db_open" >&5 echo $ECHO_N "checking for library containing db_open... $ECHO_C" >&6 if test "${ac_cv_search_db_open+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_func_search_save_LIBS=$LIBS ac_cv_search_db_open=no cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char db_open (); int main () { db_open (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_search_db_open="none required" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test "$ac_cv_search_db_open" = no; then for ac_lib in db db2; do LIBS="-l$ac_lib $ac_func_search_save_LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char db_open (); int main () { db_open (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_search_db_open="-l$ac_lib" break else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext done fi LIBS=$ac_func_search_save_LIBS fi echo "$as_me:$LINENO: result: $ac_cv_search_db_open" >&5 echo "${ECHO_T}$ac_cv_search_db_open" >&6 if test "$ac_cv_search_db_open" != no; then test "$ac_cv_search_db_open" = "none required" || LIBS="$ac_cv_search_db_open $LIBS" cs_cv_wdb=yes fi if test $cs_cv_wdb = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_DB2 1 _ACEOF EXTRA_UTL_SRC="$EXTRA_UTL_SRC wdb.c" fi fi fi; echo "$as_me:$LINENO: checking for lockf" >&5 echo $ECHO_N "checking for lockf... $ECHO_C" >&6 if test "${ac_cv_func_lockf+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define lockf to an innocuous variant, in case declares lockf. For example, HP-UX 11i declares gettimeofday. */ #define lockf innocuous_lockf /* System header to define __stub macros and hopefully few prototypes, which can conflict with char lockf (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef lockf /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char lockf (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_lockf) || defined (__stub___lockf) choke me #else char (*f) () = lockf; #endif #ifdef __cplusplus } #endif int main () { return f != lockf; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_lockf=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_lockf=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func_lockf" >&5 echo "${ECHO_T}$ac_cv_func_lockf" >&6 if test $ac_cv_func_lockf = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_LOCKF 1 _ACEOF EXTRA_UTL_SRC="$EXTRA_UTL_SRC ulocks.c rcfs.c" cs_cv_pthread=no if test "${ac_cv_header_pthread_h+set}" = set; then echo "$as_me:$LINENO: checking for pthread.h" >&5 echo $ECHO_N "checking for pthread.h... $ECHO_C" >&6 if test "${ac_cv_header_pthread_h+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 fi echo "$as_me:$LINENO: result: $ac_cv_header_pthread_h" >&5 echo "${ECHO_T}$ac_cv_header_pthread_h" >&6 else # Is the header compilable? echo "$as_me:$LINENO: checking pthread.h usability" >&5 echo $ECHO_N "checking pthread.h usability... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_header_compiler=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 echo "${ECHO_T}$ac_header_compiler" >&6 # Is the header present? echo "$as_me:$LINENO: checking pthread.h presence" >&5 echo $ECHO_N "checking pthread.h presence... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then ac_header_preproc=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 echo "${ECHO_T}$ac_header_preproc" >&6 # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) { echo "$as_me:$LINENO: WARNING: pthread.h: accepted by the compiler, rejected by the preprocessor!" >&5 echo "$as_me: WARNING: pthread.h: accepted by the compiler, rejected by the preprocessor!" >&2;} { echo "$as_me:$LINENO: WARNING: pthread.h: proceeding with the compiler's result" >&5 echo "$as_me: WARNING: pthread.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) { echo "$as_me:$LINENO: WARNING: pthread.h: present but cannot be compiled" >&5 echo "$as_me: WARNING: pthread.h: present but cannot be compiled" >&2;} { echo "$as_me:$LINENO: WARNING: pthread.h: check for missing prerequisite headers?" >&5 echo "$as_me: WARNING: pthread.h: check for missing prerequisite headers?" >&2;} { echo "$as_me:$LINENO: WARNING: pthread.h: see the Autoconf documentation" >&5 echo "$as_me: WARNING: pthread.h: see the Autoconf documentation" >&2;} { echo "$as_me:$LINENO: WARNING: pthread.h: section \"Present But Cannot Be Compiled\"" >&5 echo "$as_me: WARNING: pthread.h: section \"Present But Cannot Be Compiled\"" >&2;} { echo "$as_me:$LINENO: WARNING: pthread.h: proceeding with the preprocessor's result" >&5 echo "$as_me: WARNING: pthread.h: proceeding with the preprocessor's result" >&2;} { echo "$as_me:$LINENO: WARNING: pthread.h: in the future, the compiler will take precedence" >&5 echo "$as_me: WARNING: pthread.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------ ## ## Report this to the AC_PACKAGE_NAME lists. ## ## ------------------------------------------ ## _ASBOX ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac echo "$as_me:$LINENO: checking for pthread.h" >&5 echo $ECHO_N "checking for pthread.h... $ECHO_C" >&6 if test "${ac_cv_header_pthread_h+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_cv_header_pthread_h=$ac_header_preproc fi echo "$as_me:$LINENO: result: $ac_cv_header_pthread_h" >&5 echo "${ECHO_T}$ac_cv_header_pthread_h" >&6 fi if test $ac_cv_header_pthread_h = yes; then cs_cv_pthread=yes fi if test $cs_cv_pthread = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_PTHREADS 1 _ACEOF EXTRA_UTL_SRC="$EXTRA_UTL_SRC skiplist.c dict.c" fi fi # Make sure we can run config.sub. $ac_config_sub sun4 >/dev/null 2>&1 || { { echo "$as_me:$LINENO: error: cannot run $ac_config_sub" >&5 echo "$as_me: error: cannot run $ac_config_sub" >&2;} { (exit 1); exit 1; }; } echo "$as_me:$LINENO: checking build system type" >&5 echo $ECHO_N "checking build system type... $ECHO_C" >&6 if test "${ac_cv_build+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_cv_build_alias=$build_alias test -z "$ac_cv_build_alias" && ac_cv_build_alias=`$ac_config_guess` test -z "$ac_cv_build_alias" && { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 echo "$as_me: error: cannot guess build type; you must specify one" >&2;} { (exit 1); exit 1; }; } ac_cv_build=`$ac_config_sub $ac_cv_build_alias` || { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_build_alias failed" >&5 echo "$as_me: error: $ac_config_sub $ac_cv_build_alias failed" >&2;} { (exit 1); exit 1; }; } fi echo "$as_me:$LINENO: result: $ac_cv_build" >&5 echo "${ECHO_T}$ac_cv_build" >&6 build=$ac_cv_build build_cpu=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` build_vendor=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` build_os=`echo $ac_cv_build | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` echo "$as_me:$LINENO: checking host system type" >&5 echo $ECHO_N "checking host system type... $ECHO_C" >&6 if test "${ac_cv_host+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_cv_host_alias=$host_alias test -z "$ac_cv_host_alias" && ac_cv_host_alias=$ac_cv_build_alias ac_cv_host=`$ac_config_sub $ac_cv_host_alias` || { { echo "$as_me:$LINENO: error: $ac_config_sub $ac_cv_host_alias failed" >&5 echo "$as_me: error: $ac_config_sub $ac_cv_host_alias failed" >&2;} { (exit 1); exit 1; }; } fi echo "$as_me:$LINENO: result: $ac_cv_host" >&5 echo "${ECHO_T}$ac_cv_host" >&6 host=$ac_cv_host host_cpu=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` host_vendor=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` host_os=`echo $ac_cv_host | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` case $host_os in *mingw32* ) MINGW32=yes;; * ) MINGW32=no;; esac if test "x$MINGW32" = "xyes"; then CPPFLAGS="$CPPFLAGS -D__WINDOWS_GCC__" USE_MINGW32="USE_MINGW32 = 1" else EXTRA_UTL_SRC="$EXTRA_UTL_SRC filter.c neo_net.c neo_server.c" fi cs_cv_snprintf=no SNPRINTFOBJS="" echo "$as_me:$LINENO: checking for snprintf" >&5 echo $ECHO_N "checking for snprintf... $ECHO_C" >&6 if test "${ac_cv_func_snprintf+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define snprintf to an innocuous variant, in case declares snprintf. For example, HP-UX 11i declares gettimeofday. */ #define snprintf innocuous_snprintf /* System header to define __stub macros and hopefully few prototypes, which can conflict with char snprintf (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef snprintf /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char snprintf (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_snprintf) || defined (__stub___snprintf) choke me #else char (*f) () = snprintf; #endif #ifdef __cplusplus } #endif int main () { return f != snprintf; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_snprintf=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_snprintf=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func_snprintf" >&5 echo "${ECHO_T}$ac_cv_func_snprintf" >&6 if test $ac_cv_func_snprintf = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_SNPRINTF 1 _ACEOF else cs_cv_snprintf=yes fi echo "$as_me:$LINENO: checking for vsnprintf" >&5 echo $ECHO_N "checking for vsnprintf... $ECHO_C" >&6 if test "${ac_cv_func_vsnprintf+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define vsnprintf to an innocuous variant, in case declares vsnprintf. For example, HP-UX 11i declares gettimeofday. */ #define vsnprintf innocuous_vsnprintf /* System header to define __stub macros and hopefully few prototypes, which can conflict with char vsnprintf (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef vsnprintf /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char vsnprintf (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_vsnprintf) || defined (__stub___vsnprintf) choke me #else char (*f) () = vsnprintf; #endif #ifdef __cplusplus } #endif int main () { return f != vsnprintf; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_vsnprintf=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_vsnprintf=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func_vsnprintf" >&5 echo "${ECHO_T}$ac_cv_func_vsnprintf" >&6 if test $ac_cv_func_vsnprintf = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_VSNPRINTF 1 _ACEOF else cs_cv_snprintf=yes fi if test $cs_cv_snprintf = yes; then EXTRA_UTL_OBJS="$EXTRA_UTL_OBJS snprintf.o" fi cs_cv_missing=no cs_cv_need_reentrant=no for ac_func in localtime_r do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF echo "$as_me:$LINENO: checking whether localtime_r is declared" >&5 echo $ECHO_N "checking whether localtime_r is declared... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "localtime_r" >/dev/null 2>&1; then cat >>confdefs.h <<\_ACEOF #define HAVE_LOCALTIME_R 1 _ACEOF echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 echo "$as_me:$LINENO: checking whether localtime_r with -D_REENTRANT is declared" >&5 echo $ECHO_N "checking whether localtime_r with -D_REENTRANT is declared... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #define _REENTRANT #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "localtime_r" >/dev/null 2>&1; then cs_cv_need_reentrant=yes echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else cs_cv_missing=yes echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi rm -f conftest* fi rm -f conftest* else cs_cv_missing=yes fi done for ac_func in gmtime_r do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF echo "$as_me:$LINENO: checking whether gmtime_r is declared" >&5 echo $ECHO_N "checking whether gmtime_r is declared... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "gmtime_r" >/dev/null 2>&1; then cat >>confdefs.h <<\_ACEOF #define HAVE_GMTIME_R 1 _ACEOF echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 echo "$as_me:$LINENO: checking whether gmtime_r with -D_REENTRANT is declared" >&5 echo $ECHO_N "checking whether gmtime_r with -D_REENTRANT is declared... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #define _REENTRANT #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "gmtime_r" >/dev/null 2>&1; then cs_cv_need_reentrant=yes echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else cs_cv_missing=yes echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi rm -f conftest* fi rm -f conftest* else cs_cv_missing=yes fi done for ac_func in strtok_r do as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` echo "$as_me:$LINENO: checking for $ac_func" >&5 echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6 if eval "test \"\${$as_ac_var+set}\" = set"; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define $ac_func to an innocuous variant, in case declares $ac_func. For example, HP-UX 11i declares gettimeofday. */ #define $ac_func innocuous_$ac_func /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $ac_func (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $ac_func /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char $ac_func (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_$ac_func) || defined (__stub___$ac_func) choke me #else char (*f) () = $ac_func; #endif #ifdef __cplusplus } #endif int main () { return f != $ac_func; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then eval "$as_ac_var=yes" else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 eval "$as_ac_var=no" fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_var'}'`" >&5 echo "${ECHO_T}`eval echo '${'$as_ac_var'}'`" >&6 if test `eval echo '${'$as_ac_var'}'` = yes; then cat >>confdefs.h <<_ACEOF #define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 _ACEOF echo "$as_me:$LINENO: checking whether strtok_r is declared" >&5 echo $ECHO_N "checking whether strtok_r is declared... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "strtok_r" >/dev/null 2>&1; then cat >>confdefs.h <<\_ACEOF #define HAVE_STRTOK_R 1 _ACEOF echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 echo "$as_me:$LINENO: checking whether strtok_r with -D_REENTRANT is declared" >&5 echo $ECHO_N "checking whether strtok_r with -D_REENTRANT is declared... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #define _REENTRANT #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "strtok_r" >/dev/null 2>&1; then cs_cv_need_reentrant=yes echo "$as_me:$LINENO: result: yes" >&5 echo "${ECHO_T}yes" >&6 else cs_cv_missing=yes echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi rm -f conftest* fi rm -f conftest* else cs_cv_missing=yes fi done echo "$as_me:$LINENO: checking for mkstemp" >&5 echo $ECHO_N "checking for mkstemp... $ECHO_C" >&6 if test "${ac_cv_func_mkstemp+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define mkstemp to an innocuous variant, in case declares mkstemp. For example, HP-UX 11i declares gettimeofday. */ #define mkstemp innocuous_mkstemp /* System header to define __stub macros and hopefully few prototypes, which can conflict with char mkstemp (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef mkstemp /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char mkstemp (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_mkstemp) || defined (__stub___mkstemp) choke me #else char (*f) () = mkstemp; #endif #ifdef __cplusplus } #endif int main () { return f != mkstemp; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_mkstemp=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_mkstemp=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func_mkstemp" >&5 echo "${ECHO_T}$ac_cv_func_mkstemp" >&6 if test $ac_cv_func_mkstemp = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_MKSTEMP 1 _ACEOF else cs_cv_missing=yes fi if test $cs_cv_missing = yes; then EXTRA_UTL_OBJS="$EXTRA_UTL_OBJS missing.o" fi if test $cs_cv_need_reentrant = yes; then CPPFLAGS="$CPPFLAGS -D_REENTRANT" fi cs_cv_regex=yes echo "$as_me:$LINENO: checking for regexec" >&5 echo $ECHO_N "checking for regexec... $ECHO_C" >&6 if test "${ac_cv_func_regexec+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define regexec to an innocuous variant, in case declares regexec. For example, HP-UX 11i declares gettimeofday. */ #define regexec innocuous_regexec /* System header to define __stub macros and hopefully few prototypes, which can conflict with char regexec (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef regexec /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char regexec (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_regexec) || defined (__stub___regexec) choke me #else char (*f) () = regexec; #endif #ifdef __cplusplus } #endif int main () { return f != regexec; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_regexec=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_regexec=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func_regexec" >&5 echo "${ECHO_T}$ac_cv_func_regexec" >&6 if test $ac_cv_func_regexec = yes; then cat >>confdefs.h <<\_ACEOF #define HAVE_REGEX 1 _ACEOF else cs_cv_regex=no fi if test $cs_cv_regex = no; then CPPFLAGS="$CPPFLAGS -I\$(NEOTONIC_ROOT)/util/regex" EXTRA_UTL_SRC="$EXTRA_UTL_SRC regex/regex.c" fi cs_cv_compression=yes echo "$as_me:$LINENO: checking for deflate in -lz" >&5 echo $ECHO_N "checking for deflate in -lz... $ECHO_C" >&6 if test "${ac_cv_lib_z_deflate+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lz $LIBS" cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char deflate (); int main () { deflate (); ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_lib_z_deflate=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_lib_z_deflate=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi echo "$as_me:$LINENO: result: $ac_cv_lib_z_deflate" >&5 echo "${ECHO_T}$ac_cv_lib_z_deflate" >&6 if test $ac_cv_lib_z_deflate = yes; then cs_cv_compression=yes else cs_cv_compression=no fi # Check whether --enable-compression or --disable-compression was given. if test "${enable_compression+set}" = set; then enableval="$enable_compression" if test $enableval = no; then cs_cv_compression=no; echo "$as_me:$LINENO: result: Disabling HTML Compression support" >&5 echo "${ECHO_T}Disabling HTML Compression support" >&6 fi fi; if test $cs_cv_compression = yes; then cat >>confdefs.h <<\_ACEOF #define HTML_COMPRESSION 1 _ACEOF LIBS="$LIBS -lz" fi # Check whether --enable-remote-debugger or --disable-remote-debugger was given. if test "${enable_remote_debugger+set}" = set; then enableval="$enable_remote_debugger" if test $enableval = yes; then cat >>confdefs.h <<\_ACEOF #define ENABLE_REMOTE_DEBUG 1 _ACEOF echo "$as_me:$LINENO: result: Enabling CGI X Remote debugger" >&5 echo "${ECHO_T}Enabling CGI X Remote debugger" >&6 fi fi; cs_cv_apache=yes # Check whether --enable-apache or --disable-apache was given. if test "${enable_apache+set}" = set; then enableval="$enable_apache" if test $enableval = no; then cs_cv_apache=no; echo "$as_me:$LINENO: result: Disabling Apache 1.3.x Module" >&5 echo "${ECHO_T}Disabling Apache 1.3.x Module" >&6 fi fi; # Check whether --with-apache or --without-apache was given. if test "${with_apache+set}" = set; then withval="$with_apache" cs_cv_apache_path="$withval" else cs_cv_apache_path= fi; if test $cs_cv_apache = yes; then echo "$as_me:$LINENO: checking for apache apxs" >&5 echo $ECHO_N "checking for apache apxs... $ECHO_C" >&6 apxs_path=no apache_search_path="$cs_cv_apache_path /neo/opt /usr/local /usr" for path in $apache_search_path; do if test -x $path/httpd/bin/apxs; then apxs_path=$path/httpd/bin/apxs httpd_path=$path/httpd/bin/httpd break fi if test -x $path/httpd/sbin/apxs; then apxs_path=$path/httpd/sbin/apxs httpd_path=$path/httpd/sbin/httpd break fi if test -x $path/bin/apxs; then apxs_path=$path/bin/apxs httpd_path=$path/bin/httpd break fi if test -x $path/sbin/apxs; then apxs_path=$path/sbin/apxs httpd_path=$path/sbin/httpd break fi done if test "x$apxs_path" = "xno"; then echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 else echo "$as_me:$LINENO: result: found $apxs_path" >&5 echo "${ECHO_T}found $apxs_path" >&6 echo "$as_me:$LINENO: checking for apache 1.3.x" >&5 echo $ECHO_N "checking for apache 1.3.x... $ECHO_C" >&6 apache_version="`$httpd_path -v | grep 'Server version' | sed -e 's/.*Apache\/\([0-9]*\.[0-9]*\.[0-9]*\).*/\1/'`" apache_major_version=`echo $apache_version | sed -e 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1/'` apache_minor_version=`echo $apache_version | sed -e 's/.*\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\2/'` if test "$apache_major_version" = "1" -a "$apache_minor_version" = "3"; then echo "$as_me:$LINENO: result: found $apache_version" >&5 echo "${ECHO_T}found $apache_version" >&6 APXS_PATH="$apxs_path" BUILD_WRAPPERS="$BUILD_WRAPPERS mod_ecs" else echo "$as_me:$LINENO: result: found $apache_version - disabling module build" >&5 echo "${ECHO_T}found $apache_version - disabling module build" >&6 fi fi fi cs_cv_python=yes # Check whether --enable-python or --disable-python was given. if test "${enable_python+set}" = set; then enableval="$enable_python" if test $enableval = no; then cs_cv_python=no; echo "$as_me:$LINENO: result: Disabling python module" >&5 echo "${ECHO_T}Disabling python module" >&6 fi fi; # Check whether --with-python or --without-python was given. if test "${with_python+set}" = set; then withval="$with_python" cs_cv_python_path="$withval" else cs_cv_python_path=no fi; if test $cs_cv_python = yes; then echo "$as_me:$LINENO: checking for python includes" >&5 echo $ECHO_N "checking for python includes... $ECHO_C" >&6 python_inc=no python_lib=no python_search_path="/neo/opt /usr/local /usr /c" python_versions="2.4 2.3 2.2 2.1 2.0 1.5 24 23 22 21 20 15" if test $cs_cv_python_path != "no" -a -x $cs_cv_python_path; then python_bin=$cs_cv_python_path vers=`$python_bin -c "import sys; print sys.version[:3]"` py_inst_dir=`$python_bin -c "import sys; print sys.exec_prefix"` python_inc=$py_inst_dir/include/python$vers python_lib="-L$py_inst_dir/lib/python$vers/config -lpython$vers" python_site=$py_inst_dir/lib/python$vers/site-packages else for vers in $python_versions; do for path in $python_search_path; do if test -x $path/bin/python$vers; then python_bin=$path/bin/python$vers major_vers=`echo $vers | cut -b 1` if test $major_vers -ge 2; then python_base=`$python_bin -c "import sys, os; print os.path.dirname([x for x in sys.path if x.find('site-packages') != -1][0])"` else python_base=`$python_bin -c "import site, os; print os.path.dirname(site.sitedirs[0])"` fi if test -d $python_base; then python_lib="-L$python_base/config -lpython$vers" python_site=$python_base/site-packages fi fi if test -f $path/include/python$vers/Python.h; then python_inc=$path/include/python$vers fi if test "x$python_lib" = "xno"; then if test -d $path/lib/python$vers; then python_lib="-L$path/lib/python$vers/config -lpython$vers" python_site=$path/lib/python$vers/site-packages fi if test -d $path/lib64/python$vers; then python_lib="-L$path/lib64/python$vers/config -lpython$vers" python_site=$path/lib64/python$vers/site-packages fi fi if test -f $path/python$vers/include/Python.h; then python_inc=$path/python$vers/include python_lib="-L$path/python$vers/libs -lpython$vers" python_site=$path/python$vers/Lib/site-packages break 2 fi if test "x$python_inc" != "xno" -a "x$python_lib" != "xno"; then break 2 fi done done fi if test "x$python_inc" = "xno"; then echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 PYTHON= PYTHON_INC= PYTHON_LIB= PYTHON_SITE= else echo "$as_me:$LINENO: result: found $python_inc" >&5 echo "${ECHO_T}found $python_inc" >&6 PYTHON=$python_bin PYTHON_INC="-I$python_inc" PYTHON_LIB=$python_lib if test "x$PYTHON_SITE" = "x"; then PYTHON_SITE=$python_site fi BUILD_WRAPPERS="$BUILD_WRAPPERS python" fi fi cs_cv_perl=yes # Check whether --enable-perl or --disable-perl was given. if test "${enable_perl+set}" = set; then enableval="$enable_perl" if test $enableval = no; then cs_cv_perl=no; echo "$as_me:$LINENO: result: Disabling perl module" >&5 echo "${ECHO_T}Disabling perl module" >&6 fi fi; # Check whether --with-perl or --without-perl was given. if test "${with_perl+set}" = set; then withval="$with_perl" cs_cv_perl_path="$withval" else cs_cv_perl_path=no fi; if test $cs_cv_perl = yes; then echo "$as_me:$LINENO: checking for perl >= 5.006" >&5 echo $ECHO_N "checking for perl >= 5.006... $ECHO_C" >&6 perl_path=no perl_search_path="/neo/opt /usr/local /usr" if test $cs_cv_perl_path != "no" -a -x $cs_cv_perl_path; then perl_path=$cs_cv_perl_path else for path in $perl_search_path; do if test -x $path/bin/perl; then require_error=`$path/bin/perl -e 'require 5.006' 2>&1` if test "x$require_error" = "x"; then perl_path=$path/bin/perl break fi fi done fi if test "x$perl_path" = "xno"; then echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 PERL= else echo "$as_me:$LINENO: result: found $perl_path" >&5 echo "${ECHO_T}found $perl_path" >&6 PERL="$perl_path" BUILD_WRAPPERS="$BUILD_WRAPPERS perl" fi fi cs_cv_ruby=yes # Check whether --enable-ruby or --disable-ruby was given. if test "${enable_ruby+set}" = set; then enableval="$enable_ruby" if test $enableval = no; then cs_cv_ruby=no; echo "$as_me:$LINENO: result: Disabling ruby module" >&5 echo "${ECHO_T}Disabling ruby module" >&6 fi fi; # Check whether --with-ruby or --without-ruby was given. if test "${with_ruby+set}" = set; then withval="$with_ruby" cs_cv_ruby_path="$withval" else cs_cv_ruby_path=no fi; if test $cs_cv_ruby = yes; then echo "$as_me:$LINENO: checking for ruby" >&5 echo $ECHO_N "checking for ruby... $ECHO_C" >&6 ruby_path=no ruby_search_path="/neo/opt /usr/local /usr" if test $cs_cv_ruby_path != "no" -a -x $cs_cv_ruby_path; then ruby_path=$cs_cv_ruby_path else for path in $ruby_search_path; do if test -x $path/bin/ruby; then ruby_path=$path/bin/ruby break fi done fi if test "x$ruby_path" = "xno"; then echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 RUBY= else echo "$as_me:$LINENO: result: found $ruby_path" >&5 echo "${ECHO_T}found $ruby_path" >&6 RUBY="$ruby_path" BUILD_WRAPPERS="$BUILD_WRAPPERS ruby" fi fi cs_cv_java=yes # Check whether --enable-java or --disable-java was given. if test "${enable_java+set}" = set; then enableval="$enable_java" if test $enableval = no; then cs_cv_java=no; echo "$as_me:$LINENO: result: Disabling java module" >&5 echo "${ECHO_T}Disabling java module" >&6 fi fi; # Check whether --with-java or --without-java was given. if test "${with_java+set}" = set; then withval="$with_java" cs_cv_java_path="$withval" else cs_cv_java_path=no fi; if test $cs_cv_java = yes; then echo "$as_me:$LINENO: checking for j2sdk path" >&5 echo $ECHO_N "checking for j2sdk path... $ECHO_C" >&6 java_path=no if test $cs_cv_java_path != "no" -a -d $cs_cv_java_path; then java_path=$cs_cv_java_path else java_search_path="/neo/opt /usr/local /usr /usr/lib" for path in $java_search_path; do if test -d $path/java/j2sdk; then java_path=$path/java/j2sdk break fi if test -d $path/j2sdk; then java_path=$path/j2sdk break fi possible="$path/java/j2sdk*" for pos_path in $possible; do if test -d $pos_path; then java_path=$pos_path break 2 fi done possible="$path/j2sdk*" for pos_path in $possible; do if test -d $pos_path; then java_path=$pos_path break 2 fi done done fi if test "x$java_path" = "xno"; then echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 JAVA_PATH= JAVA_INCLUDE_PATH= else echo "$as_me:$LINENO: result: found $java_path" >&5 echo "${ECHO_T}found $java_path" >&6 JAVA_PATH="$java_path" JAVAC="$java_path/bin/javac" _ACJNI_JAVAC=$JAVAC JNI_INCLUDE_DIRS="" test "x$JAVAC" = x && { { echo "$as_me:$LINENO: error: '$JAVAC' undefined" >&5 echo "$as_me: error: '$JAVAC' undefined" >&2;} { (exit 1); exit 1; }; } # Extract the first word of "$JAVAC", so it can be a program name with args. set dummy $JAVAC; ac_word=$2 echo "$as_me:$LINENO: checking for $ac_word" >&5 echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6 if test "${ac_cv_path__ACJNI_JAVAC+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else case $_ACJNI_JAVAC in [\\/]* | ?:[\\/]*) ac_cv_path__ACJNI_JAVAC="$_ACJNI_JAVAC" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path__ACJNI_JAVAC="$as_dir/$ac_word$ac_exec_ext" echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done test -z "$ac_cv_path__ACJNI_JAVAC" && ac_cv_path__ACJNI_JAVAC="no" ;; esac fi _ACJNI_JAVAC=$ac_cv_path__ACJNI_JAVAC if test -n "$_ACJNI_JAVAC"; then echo "$as_me:$LINENO: result: $_ACJNI_JAVAC" >&5 echo "${ECHO_T}$_ACJNI_JAVAC" >&6 else echo "$as_me:$LINENO: result: no" >&5 echo "${ECHO_T}no" >&6 fi test "x$_ACJNI_JAVAC" = xno && { { echo "$as_me:$LINENO: error: $JAVAC could not be found in path" >&5 echo "$as_me: error: $JAVAC could not be found in path" >&2;} { (exit 1); exit 1; }; } # find the include directory relative to the javac executable _cur=""$_ACJNI_JAVAC"" while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do echo "$as_me:$LINENO: checking symlink for $_cur" >&5 echo $ECHO_N "checking symlink for $_cur... $ECHO_C" >&6 _slink=`ls -ld "$_cur" | sed 's/.* -> //'` case "$_slink" in /*) _cur="$_slink";; # 'X' avoids triggering unwanted echo options. *) _cur=`echo "X$_cur" | sed -e 's/^X//' -e 's:[^/]*$::'`"$_slink";; esac echo "$as_me:$LINENO: result: $_cur" >&5 echo "${ECHO_T}$_cur" >&6 done _ACJNI_FOLLOWED="$_cur" _JTOPDIR=`echo "$_ACJNI_FOLLOWED" | sed -e 's://*:/:g' -e 's:/[^/]*$::'` case "$host_os" in darwin*) _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[^/]*$::'` _JINC="$_JTOPDIR/Headers";; *) _JINC="$_JTOPDIR/include";; esac if test -f "$_JINC/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JINC" else _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[^/]*$::'` if test -f "$_JTOPDIR/include/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include" else { { echo "$as_me:$LINENO: error: cannot find java include files" >&5 echo "$as_me: error: cannot find java include files" >&2;} { (exit 1); exit 1; }; } fi fi # get the likely subdirectories for system specific java includes case "$host_os" in bsdi*) _JNI_INC_SUBDIRS="bsdos";; linux*) _JNI_INC_SUBDIRS="linux genunix";; osf*) _JNI_INC_SUBDIRS="alpha";; solaris*) _JNI_INC_SUBDIRS="solaris";; mingw*) _JNI_INC_SUBDIRS="win32";; cygwin*) _JNI_INC_SUBDIRS="win32";; *) _JNI_INC_SUBDIRS="genunix";; esac # add any subdirectories that are present for JINCSUBDIR in $_JNI_INC_SUBDIRS do if test -d "$_JTOPDIR/include/$JINCSUBDIR"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include/$JINCSUBDIR" fi done for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS do JAVA_INCLUDE_PATH="$JAVA_INCLUDE_PATH -I$JNI_INCLUDE_DIR" done BUILD_WRAPPERS="$BUILD_WRAPPERS java-jni" fi fi cs_cv_csharp=yes # Check whether --enable-csharp or --disable-csharp was given. if test "${enable_csharp+set}" = set; then enableval="$enable_csharp" if test $enableval = no; then cs_cv_csharp=no; echo "$as_me:$LINENO: result: Disabling csharp module" >&5 echo "${ECHO_T}Disabling csharp module" >&6 fi fi; # Check whether --with-csharp or --without-csharp was given. if test "${with_csharp+set}" = set; then withval="$with_csharp" cs_cv_csharp_path="$withval" else cs_cv_csharp_path=no fi; if test $cs_cv_csharp = yes; then echo "$as_me:$LINENO: checking for csharp path" >&5 echo $ECHO_N "checking for csharp path... $ECHO_C" >&6 csharp_path=no if test $cs_cv_csharp_path != "no" -a -d $cs_cv_csharp_path; then csharp_path=$cs_cv_csharp_path else csharp_search_path="/neo/opt /usr/local /usr" for path in $csharp_search_path; do if test -f $path/bin/mcs; then csharp_path=$path break fi done fi if test "x$csharp_path" = "xno"; then echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 CSHARP_PATH= else echo "$as_me:$LINENO: result: found $csharp_path/bin/mcs" >&5 echo "${ECHO_T}found $csharp_path/bin/mcs" >&6 CSHARP_PATH="$csharp_path" BUILD_WRAPPERS="$BUILD_WRAPPERS dso csharp" fi fi # Check whether --enable-gettext or --disable-gettext was given. if test "${enable_gettext+set}" = set; then enableval="$enable_gettext" if test $enableval = yes; then echo "$as_me:$LINENO: checking for gettext" >&5 echo $ECHO_N "checking for gettext... $ECHO_C" >&6 if test "${ac_cv_func_gettext+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ /* Define gettext to an innocuous variant, in case declares gettext. For example, HP-UX 11i declares gettimeofday. */ #define gettext innocuous_gettext /* System header to define __stub macros and hopefully few prototypes, which can conflict with char gettext (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef gettext /* Override any gcc2 internal prototype to avoid an error. */ #ifdef __cplusplus extern "C" { #endif /* We use char because int might match the return type of a gcc2 builtin and then its argument prototype would still apply. */ char gettext (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined (__stub_gettext) || defined (__stub___gettext) choke me #else char (*f) () = gettext; #endif #ifdef __cplusplus } #endif int main () { return f != gettext; ; return 0; } _ACEOF rm -f conftest.$ac_objext conftest$ac_exeext if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5 (eval $ac_link) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest$ac_exeext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_cv_func_gettext=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_cv_func_gettext=no fi rm -f conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi echo "$as_me:$LINENO: result: $ac_cv_func_gettext" >&5 echo "${ECHO_T}$ac_cv_func_gettext" >&6 if test $ac_cv_func_gettext = yes; then cs_cv_libintl=no if test "${ac_cv_header_libintl_h+set}" = set; then echo "$as_me:$LINENO: checking for libintl.h" >&5 echo $ECHO_N "checking for libintl.h... $ECHO_C" >&6 if test "${ac_cv_header_libintl_h+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 fi echo "$as_me:$LINENO: result: $ac_cv_header_libintl_h" >&5 echo "${ECHO_T}$ac_cv_header_libintl_h" >&6 else # Is the header compilable? echo "$as_me:$LINENO: checking libintl.h usability" >&5 echo $ECHO_N "checking libintl.h usability... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ $ac_includes_default #include _ACEOF rm -f conftest.$ac_objext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } && { ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; } && { ac_try='test -s conftest.$ac_objext' { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5 (eval $ac_try) 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); }; }; then ac_header_compiler=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_compiler=no fi rm -f conftest.err conftest.$ac_objext conftest.$ac_ext echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 echo "${ECHO_T}$ac_header_compiler" >&6 # Is the header present? echo "$as_me:$LINENO: checking libintl.h presence" >&5 echo $ECHO_N "checking libintl.h presence... $ECHO_C" >&6 cat >conftest.$ac_ext <<_ACEOF /* confdefs.h. */ _ACEOF cat confdefs.h >>conftest.$ac_ext cat >>conftest.$ac_ext <<_ACEOF /* end confdefs.h. */ #include _ACEOF if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5 (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1 ac_status=$? grep -v '^ *+' conftest.er1 >conftest.err rm -f conftest.er1 cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } >/dev/null; then if test -s conftest.err; then ac_cpp_err=$ac_c_preproc_warn_flag ac_cpp_err=$ac_cpp_err$ac_c_werror_flag else ac_cpp_err= fi else ac_cpp_err=yes fi if test -z "$ac_cpp_err"; then ac_header_preproc=yes else echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_header_preproc=no fi rm -f conftest.err conftest.$ac_ext echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 echo "${ECHO_T}$ac_header_preproc" >&6 # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in yes:no: ) { echo "$as_me:$LINENO: WARNING: libintl.h: accepted by the compiler, rejected by the preprocessor!" >&5 echo "$as_me: WARNING: libintl.h: accepted by the compiler, rejected by the preprocessor!" >&2;} { echo "$as_me:$LINENO: WARNING: libintl.h: proceeding with the compiler's result" >&5 echo "$as_me: WARNING: libintl.h: proceeding with the compiler's result" >&2;} ac_header_preproc=yes ;; no:yes:* ) { echo "$as_me:$LINENO: WARNING: libintl.h: present but cannot be compiled" >&5 echo "$as_me: WARNING: libintl.h: present but cannot be compiled" >&2;} { echo "$as_me:$LINENO: WARNING: libintl.h: check for missing prerequisite headers?" >&5 echo "$as_me: WARNING: libintl.h: check for missing prerequisite headers?" >&2;} { echo "$as_me:$LINENO: WARNING: libintl.h: see the Autoconf documentation" >&5 echo "$as_me: WARNING: libintl.h: see the Autoconf documentation" >&2;} { echo "$as_me:$LINENO: WARNING: libintl.h: section \"Present But Cannot Be Compiled\"" >&5 echo "$as_me: WARNING: libintl.h: section \"Present But Cannot Be Compiled\"" >&2;} { echo "$as_me:$LINENO: WARNING: libintl.h: proceeding with the preprocessor's result" >&5 echo "$as_me: WARNING: libintl.h: proceeding with the preprocessor's result" >&2;} { echo "$as_me:$LINENO: WARNING: libintl.h: in the future, the compiler will take precedence" >&5 echo "$as_me: WARNING: libintl.h: in the future, the compiler will take precedence" >&2;} ( cat <<\_ASBOX ## ------------------------------------------ ## ## Report this to the AC_PACKAGE_NAME lists. ## ## ------------------------------------------ ## _ASBOX ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac echo "$as_me:$LINENO: checking for libintl.h" >&5 echo $ECHO_N "checking for libintl.h... $ECHO_C" >&6 if test "${ac_cv_header_libintl_h+set}" = set; then echo $ECHO_N "(cached) $ECHO_C" >&6 else ac_cv_header_libintl_h=$ac_header_preproc fi echo "$as_me:$LINENO: result: $ac_cv_header_libintl_h" >&5 echo "${ECHO_T}$ac_cv_header_libintl_h" >&6 fi if test $ac_cv_header_libintl_h = yes; then cs_cv_libintl=yes fi if test $cs_cv_libintl = yes; then cat >>confdefs.h <<\_ACEOF #define ENABLE_GETTEXT 1 _ACEOF echo "$as_me:$LINENO: result: Enabling gettext message translation" >&5 echo "${ECHO_T}Enabling gettext message translation" >&6 else echo "$as_me:$LINENO: result: not found" >&5 echo "${ECHO_T}not found" >&6 fi fi fi fi; ac_config_files="$ac_config_files rules.mk" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, don't put newlines in cache variables' values. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. { (set) 2>&1 | case `(ac_space=' '; set | grep ac_space) 2>&1` in *ac_space=\ *) # `set' does not quote correctly, so add quotes (double-quote # substitution turns \\\\ into \\, and sed turns \\ into \). sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n \ "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p" ;; esac; } | sed ' t clear : clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ : end' >>confcache if diff $cache_file confcache >/dev/null 2>&1; then :; else if test -w $cache_file; then test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file" cat confcache >$cache_file else echo "not updating unwritable cache $cache_file" fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' # VPATH may cause trouble with some makes, so we remove $(srcdir), # ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=/{ s/:*\$(srcdir):*/:/; s/:*\${srcdir}:*/:/; s/:*@srcdir@:*/:/; s/^\([^=]*=[ ]*\):*/\1/; s/:*$//; s/^[^=]*=[ ]*$//; }' fi DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_i=`echo "$ac_i" | sed 's/\$U\././;s/\.o$//;s/\.obj$//'` # 2. Add them. ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext" ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : ${CONFIG_STATUS=./config.status} ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 echo "$as_me: creating $CONFIG_STATUS" >&6;} cat >$CONFIG_STATUS <<_ACEOF #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF ## --------------------- ## ## M4sh Initialization. ## ## --------------------- ## # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then set -o posix fi DUALCASE=1; export DUALCASE # for MKS sh # Support unset when possible. if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then as_unset=unset else as_unset=false fi # Work around bugs in pre-3.0 UWIN ksh. $as_unset ENV MAIL MAILPATH PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. for as_var in \ LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ LC_TELEPHONE LC_TIME do if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then eval $as_var=C; export $as_var else $as_unset $as_var fi done # Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1; then as_expr=expr else as_expr=false fi if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi # Name of the executable. as_me=`$as_basename "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)$' \| \ . : '\(.\)' 2>/dev/null || echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; } /^X\/\(\/\/\)$/{ s//\1/; q; } /^X\/\(\/\).*/{ s//\1/; q; } s/.*/./; q'` # PATH needs CR, and LINENO needs CR and PATH. # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then echo "#! /bin/sh" >conf$$.sh echo "exit 0" >>conf$$.sh chmod +x conf$$.sh if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then PATH_SEPARATOR=';' else PATH_SEPARATOR=: fi rm -f conf$$.sh fi as_lineno_1=$LINENO as_lineno_2=$LINENO as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` test "x$as_lineno_1" != "x$as_lineno_2" && test "x$as_lineno_3" = "x$as_lineno_2" || { # Find who we are. Look in the path if we contain no path at all # relative or not. case $0 in *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5 echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;} { (exit 1); exit 1; }; } fi case $CONFIG_SHELL in '') as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for as_base in sh bash ksh sh5; do case $as_dir in /*) if ("$as_dir/$as_base" -c ' as_lineno_1=$LINENO as_lineno_2=$LINENO as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null` test "x$as_lineno_1" != "x$as_lineno_2" && test "x$as_lineno_3" = "x$as_lineno_2" ') 2>/dev/null; then $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; } $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; } CONFIG_SHELL=$as_dir/$as_base export CONFIG_SHELL exec "$CONFIG_SHELL" "$0" ${1+"$@"} fi;; esac done done ;; esac # Create $as_me.lineno as a copy of $as_myself, but with $LINENO # uniformly replaced by the line number. The first 'sed' inserts a # line-number line before each line; the second 'sed' does the real # work. The second script uses 'N' to pair each line-number line # with the numbered line, and appends trailing '-' during # substitution so that $LINENO is not a special case at line end. # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the # second 'sed' script. Blame Lee E. McMahon for sed's syntax. :-) sed '=' <$as_myself | sed ' N s,$,-, : loop s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3, t loop s,-$,, s,^['$as_cr_digits']*\n,, ' >$as_me.lineno && chmod +x $as_me.lineno || { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5 echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;} { (exit 1); exit 1; }; } # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensible to this). . ./$as_me.lineno # Exit status is that of the last command. exit } case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in *c*,-n*) ECHO_N= ECHO_C=' ' ECHO_T=' ' ;; *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; *) ECHO_N= ECHO_C='\c' ECHO_T= ;; esac if expr a : '\(a\)' >/dev/null 2>&1; then as_expr=expr else as_expr=false fi rm -f conf$$ conf$$.exe conf$$.file echo >conf$$.file if ln -s conf$$.file conf$$ 2>/dev/null; then # We could just check for DJGPP; but this test a) works b) is more generic # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04). if test -f conf$$.exe; then # Don't use ln at all; we don't have any links as_ln_s='cp -p' else as_ln_s='ln -s' fi elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -p' fi rm -f conf$$ conf$$.exe conf$$.file if mkdir -p . 2>/dev/null; then as_mkdir_p=: else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_executable_p="test -f" # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" # IFS # We need space, tab and new line, in precisely that order. as_nl=' ' IFS=" $as_nl" # CDPATH. $as_unset CDPATH exec 6>&1 # Open the log real soon, to keep \$[0] and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. Logging --version etc. is OK. exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX } >&5 cat >&5 <<_CSEOF This file was extended by $as_me, which was generated by GNU Autoconf 2.59. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ _CSEOF echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5 echo >&5 _ACEOF # Files that config.status was made for. if test -n "$ac_config_files"; then echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS fi if test -n "$ac_config_headers"; then echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS fi if test -n "$ac_config_links"; then echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS fi if test -n "$ac_config_commands"; then echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS fi cat >>$CONFIG_STATUS <<\_ACEOF ac_cs_usage="\ \`$as_me' instantiates files from templates according to the current configuration. Usage: $0 [OPTIONS] [FILE]... -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF ac_cs_version="\\ config.status configured by $0, generated by GNU Autoconf 2.59, with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\" Copyright (C) 2003 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." srcdir=$srcdir INSTALL="$INSTALL" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF # If no file are specified by the user, then we need to provide default # value. By we need to know if files were specified by the user. ac_need_defaults=: while test $# != 0 do case $1 in --*=*) ac_option=`expr "x$1" : 'x\([^=]*\)='` ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'` ac_shift=: ;; -*) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; *) # This is not an option, so the user has probably given explicit # arguments. ac_option=$1 ac_need_defaults=false;; esac case $ac_option in # Handling of the options. _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --vers* | -V ) echo "$ac_cs_version"; exit 0 ;; --he | --h) # Conflict between --help and --header { { echo "$as_me:$LINENO: error: ambiguous option: $1 Try \`$0 --help' for more information." >&5 echo "$as_me: error: ambiguous option: $1 Try \`$0 --help' for more information." >&2;} { (exit 1); exit 1; }; };; --help | --hel | -h ) echo "$ac_cs_usage"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift CONFIG_FILES="$CONFIG_FILES $ac_optarg" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" ac_need_defaults=false;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1 Try \`$0 --help' for more information." >&5 echo "$as_me: error: unrecognized option: $1 Try \`$0 --help' for more information." >&2;} { (exit 1); exit 1; }; } ;; *) ac_config_targets="$ac_config_targets $1" ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF if \$ac_cs_recheck; then echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF for ac_config_target in $ac_config_targets do case "$ac_config_target" in # Handling of arguments. "rules.mk" ) CONFIG_FILES="$CONFIG_FILES rules.mk" ;; "cs_config.h" ) CONFIG_HEADERS="$CONFIG_HEADERS cs_config.h" ;; *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 echo "$as_me: error: invalid argument: $ac_config_target" >&2;} { (exit 1); exit 1; }; };; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason to put it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Create a temporary directory, and hook for its removal unless debugging. $debug || { trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0 trap '{ (exit 1); exit 1; }' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" } || { tmp=./confstat$$-$RANDOM (umask 077 && mkdir $tmp) } || { echo "$me: cannot create a temporary directory in ." >&2 { (exit 1); exit 1; } } _ACEOF cat >>$CONFIG_STATUS <<_ACEOF # # CONFIG_FILES section. # # No need to generate the scripts if there are no CONFIG_FILES. # This happens for instance when ./config.status config.h if test -n "\$CONFIG_FILES"; then # Protect against being on the right side of a sed subst in config.status. sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g; s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF s,@SHELL@,$SHELL,;t t s,@PATH_SEPARATOR@,$PATH_SEPARATOR,;t t s,@PACKAGE_NAME@,$PACKAGE_NAME,;t t s,@PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t s,@PACKAGE_VERSION@,$PACKAGE_VERSION,;t t s,@PACKAGE_STRING@,$PACKAGE_STRING,;t t s,@PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t s,@exec_prefix@,$exec_prefix,;t t s,@prefix@,$prefix,;t t s,@program_transform_name@,$program_transform_name,;t t s,@bindir@,$bindir,;t t s,@sbindir@,$sbindir,;t t s,@libexecdir@,$libexecdir,;t t s,@datadir@,$datadir,;t t s,@sysconfdir@,$sysconfdir,;t t s,@sharedstatedir@,$sharedstatedir,;t t s,@localstatedir@,$localstatedir,;t t s,@libdir@,$libdir,;t t s,@includedir@,$includedir,;t t s,@oldincludedir@,$oldincludedir,;t t s,@infodir@,$infodir,;t t s,@mandir@,$mandir,;t t s,@build_alias@,$build_alias,;t t s,@host_alias@,$host_alias,;t t s,@target_alias@,$target_alias,;t t s,@DEFS@,$DEFS,;t t s,@ECHO_C@,$ECHO_C,;t t s,@ECHO_N@,$ECHO_N,;t t s,@ECHO_T@,$ECHO_T,;t t s,@LIBS@,$LIBS,;t t s,@CC@,$CC,;t t s,@CFLAGS@,$CFLAGS,;t t s,@LDFLAGS@,$LDFLAGS,;t t s,@CPPFLAGS@,$CPPFLAGS,;t t s,@ac_ct_CC@,$ac_ct_CC,;t t s,@EXEEXT@,$EXEEXT,;t t s,@OBJEXT@,$OBJEXT,;t t s,@CPP@,$CPP,;t t s,@LN_S@,$LN_S,;t t s,@AR@,$AR,;t t s,@RANLIB@,$RANLIB,;t t s,@ac_ct_RANLIB@,$ac_ct_RANLIB,;t t s,@SET_MAKE@,$SET_MAKE,;t t s,@INSTALL_PROGRAM@,$INSTALL_PROGRAM,;t t s,@INSTALL_SCRIPT@,$INSTALL_SCRIPT,;t t s,@INSTALL_DATA@,$INSTALL_DATA,;t t s,@EGREP@,$EGREP,;t t s,@build@,$build,;t t s,@build_cpu@,$build_cpu,;t t s,@build_vendor@,$build_vendor,;t t s,@build_os@,$build_os,;t t s,@host@,$host,;t t s,@host_cpu@,$host_cpu,;t t s,@host_vendor@,$host_vendor,;t t s,@host_os@,$host_os,;t t s,@_ACJNI_JAVAC@,$_ACJNI_JAVAC,;t t s,@USE_MINGW32@,$USE_MINGW32,;t t s,@APXS_PATH@,$APXS_PATH,;t t s,@PERL@,$PERL,;t t s,@RUBY@,$RUBY,;t t s,@BUILD_WRAPPERS@,$BUILD_WRAPPERS,;t t s,@JAVA_PATH@,$JAVA_PATH,;t t s,@JAVA_INCLUDE_PATH@,$JAVA_INCLUDE_PATH,;t t s,@PYTHON@,$PYTHON,;t t s,@PYTHON_INC@,$PYTHON_INC,;t t s,@PYTHON_LIB@,$PYTHON_LIB,;t t s,@PYTHON_SITE@,$PYTHON_SITE,;t t s,@EXTRA_UTL_SRC@,$EXTRA_UTL_SRC,;t t s,@EXTRA_UTL_OBJS@,$EXTRA_UTL_OBJS,;t t s,@CSHARP_PATH@,$CSHARP_PATH,;t t s,@LIBOBJS@,$LIBOBJS,;t t s,@LTLIBOBJS@,$LTLIBOBJS,;t t CEOF _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF # Split the substitutions into bite-sized pieces for seds with # small command number limits, like on Digital OSF/1 and HP-UX. ac_max_sed_lines=48 ac_sed_frag=1 # Number of current file. ac_beg=1 # First line for current file. ac_end=$ac_max_sed_lines # Line after last line for current file. ac_more_lines=: ac_sed_cmds= while $ac_more_lines; do if test $ac_beg -gt 1; then sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag else sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag fi if test ! -s $tmp/subs.frag; then ac_more_lines=false else # The purpose of the label and of the branching condition is to # speed up the sed processing (if there are no `@' at all, there # is no need to browse any of the substitutions). # These are the two extra sed commands mentioned above. (echo ':t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed if test -z "$ac_sed_cmds"; then ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed" else ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed" fi ac_sed_frag=`expr $ac_sed_frag + 1` ac_beg=$ac_end ac_end=`expr $ac_end + $ac_max_sed_lines` fi done if test -z "$ac_sed_cmds"; then ac_sed_cmds=cat fi fi # test -n "$CONFIG_FILES" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in". case $ac_file in - | *:- | *:-:* ) # input from stdin cat >$tmp/stdin ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; * ) ac_file_in=$ac_file.in ;; esac # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories. ac_dir=`(dirname "$ac_file") 2>/dev/null || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| \ . : '\(.\)' 2>/dev/null || echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } /^X\(\/\/\)[^/].*/{ s//\1/; q; } /^X\(\/\/\)$/{ s//\1/; q; } /^X\(\/\).*/{ s//\1/; q; } s/.*/./; q'` { if $as_mkdir_p; then mkdir -p "$ac_dir" else as_dir="$ac_dir" as_dirs= while test ! -d "$as_dir"; do as_dirs="$as_dir $as_dirs" as_dir=`(dirname "$as_dir") 2>/dev/null || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| \ . : '\(.\)' 2>/dev/null || echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } /^X\(\/\/\)[^/].*/{ s//\1/; q; } /^X\(\/\/\)$/{ s//\1/; q; } /^X\(\/\).*/{ s//\1/; q; } s/.*/./; q'` done test ! -n "$as_dirs" || mkdir $as_dirs fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} { (exit 1); exit 1; }; }; } ac_builddir=. if test "$ac_dir" != .; then ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` # A "../" for each directory in $ac_dir_suffix. ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'` else ac_dir_suffix= ac_top_builddir= fi case $srcdir in .) # No --srcdir option. We are building in place. ac_srcdir=. if test -z "$ac_top_builddir"; then ac_top_srcdir=. else ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'` fi ;; [\\/]* | ?:[\\/]* ) # Absolute path. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ;; *) # Relative path. ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_builddir$srcdir ;; esac # Do not use `cd foo && pwd` to compute absolute paths, because # the directories may not exist. case `pwd` in .) ac_abs_builddir="$ac_dir";; *) case "$ac_dir" in .) ac_abs_builddir=`pwd`;; [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";; *) ac_abs_builddir=`pwd`/"$ac_dir";; esac;; esac case $ac_abs_builddir in .) ac_abs_top_builddir=${ac_top_builddir}.;; *) case ${ac_top_builddir}. in .) ac_abs_top_builddir=$ac_abs_builddir;; [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;; *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;; esac;; esac case $ac_abs_builddir in .) ac_abs_srcdir=$ac_srcdir;; *) case $ac_srcdir in .) ac_abs_srcdir=$ac_abs_builddir;; [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;; *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;; esac;; esac case $ac_abs_builddir in .) ac_abs_top_srcdir=$ac_top_srcdir;; *) case $ac_top_srcdir in .) ac_abs_top_srcdir=$ac_abs_builddir;; [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;; *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;; esac;; esac case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_builddir$INSTALL ;; esac # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ if test x"$ac_file" = x-; then configure_input= else configure_input="$ac_file. " fi configure_input=$configure_input"Generated from `echo $ac_file_in | sed 's,.*/,,'` by configure." # First look for the input files in the build tree, otherwise in the # src tree. ac_file_inputs=`IFS=: for f in $ac_file_in; do case $f in -) echo $tmp/stdin ;; [\\/$]*) # Absolute (can't be DOS-style, as IFS=:) test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 echo "$as_me: error: cannot find input file: $f" >&2;} { (exit 1); exit 1; }; } echo "$f";; *) # Relative if test -f "$f"; then # Build tree echo "$f" elif test -f "$srcdir/$f"; then # Source tree echo "$srcdir/$f" else # /dev/null tree { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 echo "$as_me: error: cannot find input file: $f" >&2;} { (exit 1); exit 1; }; } fi;; esac done` || { (exit 1); exit 1; } if test x"$ac_file" != x-; then { echo "$as_me:$LINENO: creating $ac_file" >&5 echo "$as_me: creating $ac_file" >&6;} rm -f "$ac_file" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF sed "$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s,@configure_input@,$configure_input,;t t s,@srcdir@,$ac_srcdir,;t t s,@abs_srcdir@,$ac_abs_srcdir,;t t s,@top_srcdir@,$ac_top_srcdir,;t t s,@abs_top_srcdir@,$ac_abs_top_srcdir,;t t s,@builddir@,$ac_builddir,;t t s,@abs_builddir@,$ac_abs_builddir,;t t s,@top_builddir@,$ac_top_builddir,;t t s,@abs_top_builddir@,$ac_abs_top_builddir,;t t s,@INSTALL@,$ac_INSTALL,;t t " $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out rm -f $tmp/stdin if test x"$ac_file" != x-; then mv $tmp/out $ac_file else cat $tmp/out rm -f $tmp/out fi done _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF # # CONFIG_HEADER section. # # These sed commands are passed to sed as "A NAME B NAME C VALUE D", where # NAME is the cpp macro being defined and VALUE is the value it is being given. # # ac_d sets the value in "#define NAME VALUE" lines. ac_dA='s,^\([ ]*\)#\([ ]*define[ ][ ]*\)' ac_dB='[ ].*$,\1#\2' ac_dC=' ' ac_dD=',;t' # ac_u turns "#undef NAME" without trailing blanks into "#define NAME VALUE". ac_uA='s,^\([ ]*\)#\([ ]*\)undef\([ ][ ]*\)' ac_uB='$,\1#\2define\3' ac_uC=' ' ac_uD=',;t' for ac_file in : $CONFIG_HEADERS; do test "x$ac_file" = x: && continue # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in". case $ac_file in - | *:- | *:-:* ) # input from stdin cat >$tmp/stdin ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'` ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;; * ) ac_file_in=$ac_file.in ;; esac test x"$ac_file" != x- && { echo "$as_me:$LINENO: creating $ac_file" >&5 echo "$as_me: creating $ac_file" >&6;} # First look for the input files in the build tree, otherwise in the # src tree. ac_file_inputs=`IFS=: for f in $ac_file_in; do case $f in -) echo $tmp/stdin ;; [\\/$]*) # Absolute (can't be DOS-style, as IFS=:) test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 echo "$as_me: error: cannot find input file: $f" >&2;} { (exit 1); exit 1; }; } # Do quote $f, to prevent DOS paths from being IFS'd. echo "$f";; *) # Relative if test -f "$f"; then # Build tree echo "$f" elif test -f "$srcdir/$f"; then # Source tree echo "$srcdir/$f" else # /dev/null tree { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5 echo "$as_me: error: cannot find input file: $f" >&2;} { (exit 1); exit 1; }; } fi;; esac done` || { (exit 1); exit 1; } # Remove the trailing spaces. sed 's/[ ]*$//' $ac_file_inputs >$tmp/in _ACEOF # Transform confdefs.h into two sed scripts, `conftest.defines' and # `conftest.undefs', that substitutes the proper values into # config.h.in to produce config.h. The first handles `#define' # templates, and the second `#undef' templates. # And first: Protect against being on the right side of a sed subst in # config.status. Protect against being in an unquoted here document # in config.status. rm -f conftest.defines conftest.undefs # Using a here document instead of a string reduces the quoting nightmare. # Putting comments in sed scripts is not portable. # # `end' is used to avoid that the second main sed command (meant for # 0-ary CPP macros) applies to n-ary macro definitions. # See the Autoconf documentation for `clear'. cat >confdef2sed.sed <<\_ACEOF s/[\\&,]/\\&/g s,[\\$`],\\&,g t clear : clear s,^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*\)\(([^)]*)\)[ ]*\(.*\)$,${ac_dA}\1${ac_dB}\1\2${ac_dC}\3${ac_dD},gp t end s,^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)$,${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD},gp : end _ACEOF # If some macros were called several times there might be several times # the same #defines, which is useless. Nevertheless, we may not want to # sort them, since we want the *last* AC-DEFINE to be honored. uniq confdefs.h | sed -n -f confdef2sed.sed >conftest.defines sed 's/ac_d/ac_u/g' conftest.defines >conftest.undefs rm -f confdef2sed.sed # This sed command replaces #undef with comments. This is necessary, for # example, in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. cat >>conftest.undefs <<\_ACEOF s,^[ ]*#[ ]*undef[ ][ ]*[a-zA-Z_][a-zA-Z_0-9]*,/* & */, _ACEOF # Break up conftest.defines because some shells have a limit on the size # of here documents, and old seds have small limits too (100 cmds). echo ' # Handle all the #define templates only if necessary.' >>$CONFIG_STATUS echo ' if grep "^[ ]*#[ ]*define" $tmp/in >/dev/null; then' >>$CONFIG_STATUS echo ' # If there are no defines, we may have an empty if/fi' >>$CONFIG_STATUS echo ' :' >>$CONFIG_STATUS rm -f conftest.tail while grep . conftest.defines >/dev/null do # Write a limited-size here document to $tmp/defines.sed. echo ' cat >$tmp/defines.sed <>$CONFIG_STATUS # Speed up: don't consider the non `#define' lines. echo '/^[ ]*#[ ]*define/!b' >>$CONFIG_STATUS # Work around the forget-to-reset-the-flag bug. echo 't clr' >>$CONFIG_STATUS echo ': clr' >>$CONFIG_STATUS sed ${ac_max_here_lines}q conftest.defines >>$CONFIG_STATUS echo 'CEOF sed -f $tmp/defines.sed $tmp/in >$tmp/out rm -f $tmp/in mv $tmp/out $tmp/in ' >>$CONFIG_STATUS sed 1,${ac_max_here_lines}d conftest.defines >conftest.tail rm -f conftest.defines mv conftest.tail conftest.defines done rm -f conftest.defines echo ' fi # grep' >>$CONFIG_STATUS echo >>$CONFIG_STATUS # Break up conftest.undefs because some shells have a limit on the size # of here documents, and old seds have small limits too (100 cmds). echo ' # Handle all the #undef templates' >>$CONFIG_STATUS rm -f conftest.tail while grep . conftest.undefs >/dev/null do # Write a limited-size here document to $tmp/undefs.sed. echo ' cat >$tmp/undefs.sed <>$CONFIG_STATUS # Speed up: don't consider the non `#undef' echo '/^[ ]*#[ ]*undef/!b' >>$CONFIG_STATUS # Work around the forget-to-reset-the-flag bug. echo 't clr' >>$CONFIG_STATUS echo ': clr' >>$CONFIG_STATUS sed ${ac_max_here_lines}q conftest.undefs >>$CONFIG_STATUS echo 'CEOF sed -f $tmp/undefs.sed $tmp/in >$tmp/out rm -f $tmp/in mv $tmp/out $tmp/in ' >>$CONFIG_STATUS sed 1,${ac_max_here_lines}d conftest.undefs >conftest.tail rm -f conftest.undefs mv conftest.tail conftest.undefs done rm -f conftest.undefs cat >>$CONFIG_STATUS <<\_ACEOF # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ if test x"$ac_file" = x-; then echo "/* Generated by configure. */" >$tmp/config.h else echo "/* $ac_file. Generated by configure. */" >$tmp/config.h fi cat $tmp/in >>$tmp/config.h rm -f $tmp/in if test x"$ac_file" != x-; then if diff $ac_file $tmp/config.h >/dev/null 2>&1; then { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 echo "$as_me: $ac_file is unchanged" >&6;} else ac_dir=`(dirname "$ac_file") 2>/dev/null || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| \ . : '\(.\)' 2>/dev/null || echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } /^X\(\/\/\)[^/].*/{ s//\1/; q; } /^X\(\/\/\)$/{ s//\1/; q; } /^X\(\/\).*/{ s//\1/; q; } s/.*/./; q'` { if $as_mkdir_p; then mkdir -p "$ac_dir" else as_dir="$ac_dir" as_dirs= while test ! -d "$as_dir"; do as_dirs="$as_dir $as_dirs" as_dir=`(dirname "$as_dir") 2>/dev/null || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| \ . : '\(.\)' 2>/dev/null || echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; } /^X\(\/\/\)[^/].*/{ s//\1/; q; } /^X\(\/\/\)$/{ s//\1/; q; } /^X\(\/\).*/{ s//\1/; q; } s/.*/./; q'` done test ! -n "$as_dirs" || mkdir $as_dirs fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5 echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;} { (exit 1); exit 1; }; }; } rm -f $ac_file mv $tmp/config.h $ac_file fi else cat $tmp/config.h rm -f $tmp/config.h fi done _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF { (exit 0); exit 0; } _ACEOF chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || { (exit 1); exit 1; } fi clearsilver-0.10.5/man/0000755001211700116100000000000010645505100011653 500000000000000clearsilver-0.10.5/man/man3/0000755001211700116100000000000010645505100012511 500000000000000clearsilver-0.10.5/man/man3/dictDestroy.30000644001211700116100000000111310645505100015006 00000000000000.TH dictDestroy 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictDestroy - destroy dictionary. .SH SYNOPSIS .Ss #include .Se .Ss void dictDestroy(dictCtx dict); .Se .SH ARGUMENTS dict - dictionary to destroy .SH DESCRIPTION Release all resources used by . MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictCleanup.30000644001211700116100000000136410645505100014754 00000000000000.TH dictCleanup 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictCleanup - cleanup dictionary .SH SYNOPSIS .Ss #include .Se .Ss void dictCleanup(dictCtx dict, dictCleanupFunc cleanup, void *rock); .Se .SH ARGUMENTS dict - dictionary to cleanup .br cleanup - cleanup callback .br rock - to pass to .SH DESCRIPTION Calls for every item in . If returns true, then item is removed from . MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictReleaseLock.30000644001211700116100000000142310645505100015552 00000000000000.TH dictReleaseLock 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictReleaseLock - release lock on value. .SH SYNOPSIS .Ss #include .Se .Ss void dictReleaseLock(dictCtx dict, void *lock); .Se .SH ARGUMENTS dict - dictionary containing value to release. .br lock - lock to release. .SH DESCRIPTION Releases the lock on the value associated with . Once the lock is released, the dictCleanupFunc callback can be called for the value (see dictCleanup()). MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictRemove.30000644001211700116100000000122610645505100014617 00000000000000.TH dictRemove 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictRemove - remove item from dictionary. .SH SYNOPSIS .Ss #include .Se .Ss BOOL dictRemove(dictCtx dict, const char *id); .Se .SH ARGUMENTS dict - dictionary to search in. .br id - identifier of item to remove. .SH DESCRIPTION Removes item identified by from . MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictNext.30000644001211700116100000000227210645505100014302 00000000000000.TH dictNext 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictNext - search for next value in dictionary. .SH SYNOPSIS .Ss #include .Se .Ss void *dictNext(dictCtx dict, char **id, void **plock); .Se .SH ARGUMENTS dict - dictionary to iterate over. .br id - pointer to identifier of last item found, or .br pointer to NULL to retrieve first. .br plock - place for value lock (or NULL). .SH DESCRIPTION Can be used to iterate through values in the dictionary. The order is the order of the hash of the ids, which isn't usefully externally. Will return the value if found, or NULL if not. If is non-NULL, then the lock returned in will be associated with the returned value. Until this lock is passed to dictReleaseLock(), the value will not be passed to the dictCleanupFunc callback (see dictCleanup()). MT-Level: Safe if thread-safe. .SH "RETURN VALUE" plock - set to value lock. .br id - pointer to id of found value .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictCreate.30000644001211700116100000000221010645505100014557 00000000000000.TH dictCreate 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictCreate - create new dictionary. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *dictCreate(dictCtx *dict, BOOL threaded, UINT32 root, UINT32 maxLevel, UINT32 flushLimit, BOOL useCase, dictFreeValueFunc freeValue, void *freeRock); .Se .SH ARGUMENTS threaded - true if list should be thread-safe. .br root - performance parameter (see above). .br maxLevel - performance parameter (see above). .br flushLimit - max deleted items to keep cached before .br forcing a flush. .br useCase - true to be case sensitive in identifiers .br freeValue - callback when freeing a value .br freeRock - context for freeValue callback .SH DESCRIPTION Returns a dictionary. If is true, list is multi-thread safe. , , and act as for skipNewList() (see skiplist.h) MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictSetValue.30000644001211700116100000000137510645505100015117 00000000000000.TH dictSetValue 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictSetValue - set/reset an items value. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *dictSetValue(dictCtx dict, const char *id, void *value); .Se .SH ARGUMENTS dict - dictionary to add pair to. .br id - identifier to insert/update .br value - value to store (may NOT be NULL) .SH DESCRIPTION Updates the / pair into . If is not in , it is created. MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictModifyValue.30000644001211700116100000000177210645505100015614 00000000000000.TH dictModifyValue 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictModifyValue - create/modify an item. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *dictModifyValue(dictCtx dict, const char *id, dictNewValueCB new_cb, dictUpdateValueCB update, void *rock); .Se .SH ARGUMENTS dict - dictionary to add pair to. .br id - identifier of value .br new - function to call to create new value (may be NULL) .br update - function to call to modify value (if NULL, the old .br value is freed, and is used) .br rock - context to pass to or . .SH DESCRIPTION Finds 's value and calls . If is not in , calls to obtain a new value. MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/dictSearch.30000644001211700116100000000175610645505100014577 00000000000000.TH dictSearch 3 "12 July 2007" "ClearSilver" "util/dict.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME dictSearch - search for value in dictionary. .SH SYNOPSIS .Ss #include .Se .Ss void *dictSearch(dictCtx dict, const char *id, void **plock); .Se .SH ARGUMENTS dict - dictionary to search in. .br id - identifier of item to find. .br plock - place for value lock (or NULL). .SH DESCRIPTION Searches for in , and returns value if found, or NULL if not. If is non-NULL, then the lock returned in will be associated with the returned value. Until this lock is passed to dictReleaseLock(), the value will not be passed to the dictCleanupFunc callback (see dictCleanup()). MT-Level: Safe if thread-safe. .SH "RETURN VALUE" plock - set to value lock. .SH "SEE ALSO" .BR dictDestroy "(3), "dictCleanup "(3), "dictReleaseLock "(3), "dictRemove "(3), "dictNext "(3), "dictCreate "(3), "dictSetValue "(3), "dictModifyValue "(3), "dictSearch clearsilver-0.10.5/man/man3/filter_wait.30000644001211700116100000000157010645505100015031 00000000000000.TH filter_wait 3 "12 July 2007" "ClearSilver" "util/filter.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME filter_wait - wrap waitpid to decode the exitcode and why your filter quit .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *filter_wait(pid_t pid, int options, int *exitcode); .Se .SH ARGUMENTS pid -> the process identifier to wait for .br options -> the options to pass to waitpid (see wait(2)) .SH DESCRIPTION filter_wait wraps the waitpid call and raises an error (with description) if the call failed. Note that if the ask for the exitcode and the process exited with a code other than zero, we don't raise an error. If you don't ask for the exitcode, and it is non-zero, we raise an error .SH "RETURN VALUE" exitcode -> the exitcode if the process existed normally .SH "SEE ALSO" .BR filter_wait "(3), "filter_create_fp "(3), "filter_create_fd clearsilver-0.10.5/man/man3/filter_create_fp.30000644001211700116100000000215710645505100016017 00000000000000.TH filter_create_fp 3 "12 July 2007" "ClearSilver" "util/filter.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME filter_create_fp - similar to filter_create_fd except with buffered FILE* .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *filter_create_fp(const char *cmd, FILE **in, FILE **out, FILE **err, pid_t *pid); .Se .SH ARGUMENTS cmd -> the sub command to execute. Will be executed with .br /bin/sh -c .br in -> pointer to return the stdin pipe, or NULL if you don't .br want the stdin pipe .br out -> pointer to return the stdout pipe, or NULL if you don't .br want the stdout pipe .br err -> pointer to return the stderr pipe, or NULL if you don't .br want the stderr pipe .SH DESCRIPTION filter_create_fp is identical to filter_create_fd, except each of the pipes is wrapped in a buffered stdio FILE .SH "RETURN VALUE" in -> the stdin FILE of the sub process .br out -> the stdout FILE of the sub process .br err -> the stderr FILE of the sub process .br pid -> the pid of the sub process .SH "SEE ALSO" .BR filter_wait "(3), "filter_create_fp "(3), "filter_create_fd clearsilver-0.10.5/man/man3/filter_create_fd.30000644001211700116100000000306010645505100015775 00000000000000.TH filter_create_fd 3 "12 July 2007" "ClearSilver" "util/filter.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME filter_create_fd - Create a sub process and return the requested pipes .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *filter_create_fd(const char *cmd, int *fdin, int *fdout, int *fderr, pid_t *pid); .Se .SH ARGUMENTS cmd -> the sub command to execute. Will be executed with .br /bin/sh -c .br fdin -> pointer to return the stdin pipe, or NULL if you don't .br want the stdin pipe .br fdout -> pointer to return the stdout pipe, or NULL if you don't .br want the stdout pipe .br fderr -> pointer to return the stderr pipe, or NULL if you don't .br want the stderr pipe .SH DESCRIPTION filter_create_fd and filter_create_fp are what popen been: a mechanism to create sub processes and have pipes to all their input/output. The concept was taken from mutt, though python has something similar with popen3/popen4. You control which pipes the function returns by the fdin/fdout/fderr arguments. A NULL value means "don't create a pipe", a pointer to an int will cause the pipes to be created and the value of the file descriptor stored in the int. You will have to close(2) the file descriptors yourself. .SH "RETURN VALUE" fdin -> the stdin file descriptor of the sub process .br fdout -> the stdout file descriptor of the sub process .br fderr -> the stderr file descriptor of the sub process .br pid -> the pid of the sub process .SH "SEE ALSO" .BR filter_wait "(3), "filter_create_fp "(3), "filter_create_fd clearsilver-0.10.5/man/man3/nerr_error_traceback.30000644001211700116100000000121610645505100016673 00000000000000.TH nerr_error_traceback 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_error_traceback .SH SYNOPSIS .Ss #include .Se .Ss void nerr_error_traceback (NEOERR *err, STRING *str); .Se .SH ARGUMENTS err - error .br str - string to which the data is appended .SH DESCRIPTION returns the full traceback of the error chain .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_pass.30000644001211700116100000000137510645505100014517 00000000000000.TH nerr_pass 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_pass .SH SYNOPSIS .Ss #include .Se .Ss nerr_pass() .Se .SH ARGUMENTS with the macro, the function name, file and lineno are .br automagically recorded. Just pass the error. .SH DESCRIPTION this function is used to pass an error up a level in the call chain (ie, if the error isn't handled at the current level). This allows us to track the traceback of the error. .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_error_string.30000644001211700116100000000125110645505100016261 00000000000000.TH nerr_error_string 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_error_string .SH SYNOPSIS .Ss #include .Se .Ss void nerr_error_string (NEOERR *err, STRING *str); .Se .SH ARGUMENTS err - error .br str - string to which the data is appended .SH DESCRIPTION returns the string associated with an error (the bottom level of the error chain) .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_pass_ctx.30000644001211700116100000000164310645505100015373 00000000000000.TH nerr_pass_ctx 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_pass_ctx .SH SYNOPSIS .Ss #include .Se .Ss nerr_pass_ctx() .Se .SH ARGUMENTS with the macro, the function name, file and lineno are .br automagically recorded. Just pass the error and .br a printf format string giving more information about where .br the error is occuring. .SH DESCRIPTION this function is used to pass an error up a level in the call chain (ie, if the error isn't handled at the current level). This allows us to track the traceback of the error. This version includes context information about lower errors .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_init.30000644001211700116100000000134710645505100014513 00000000000000.TH nerr_init 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_init .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *nerr_init (void); .Se .SH ARGUMENTS None .SH DESCRIPTION initialize the NEOERR system. Can be called more than once. Is not thread safe. This registers all of the built in error types as defined at the top of this file. If you don't call this, all exceptions will be returned as UnknownError. .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_match.30000644001211700116100000000157610645505100014650 00000000000000.TH nerr_match 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_match .SH SYNOPSIS .Ss #include .Se .Ss int nerr_match (NEOERR *err, NERR_TYPE type); .Se .SH ARGUMENTS err - the NEOERR that has an error. .br type - the NEOERR type, as registered with nerr_register .SH DESCRIPTION nerr_match is used to walk the NEOERR chain and match the error against a specific error type. In exception parlance, this would be the equivalent of "catch". Typically, you can just compare a NEOERR against STATUS_OK or just test for true if you are checking for any error. .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_log_error.30000644001211700116100000000110210645505100015527 00000000000000.TH nerr_log_error 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_log_error .SH SYNOPSIS .Ss #include .Se .Ss void nerr_log_error (NEOERR *err); .Se .SH DESCRIPTION currently, this prints out the error to stderr, and free's the error chain .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_ignore.30000644001211700116100000000113210645505100015023 00000000000000.TH nerr_ignore 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_ignore .SH SYNOPSIS .Ss #include .Se .Ss void nerr_ignore (NEOERR **err); .Se .SH DESCRIPTION you should only call this if you actually handle the error (should I rename it?). Free's the error chain. .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_register.30000644001211700116100000000132510645505100015370 00000000000000.TH nerr_register 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_register .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *nerr_register (NERR_TYPE *err, const char *name); .Se .SH ARGUMENTS err - pointer to a NERR_TYPE .br name - pretty name for the error type .SH DESCRIPTION register an error type. This will assign a numeric value to the type, and keep track of the "pretty name" for it. .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/nerr_handle.30000644001211700116100000000136010645505100014776 00000000000000.TH nerr_handle 3 "12 July 2007" "ClearSilver" "util/neo_err.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME nerr_handle .SH SYNOPSIS .Ss #include .Se .Ss int nerr_handle (NEOERR **err, NERR_TYPE type); .Se .SH ARGUMENTS err - pointer to a pointer NEOERR .br type - the NEOERR type, as registered with nerr_register .SH DESCRIPTION nerr_handle is a convenience function. It is the equivalent of nerr_match, but it will also deallocate the error chain on a match. .SH "SEE ALSO" .BR nerr_error_traceback "(3), "nerr_pass "(3), "nerr_error_string "(3), "defined "(3), "nerr_pass_ctx "(3), "nerr_passf "(3), "nerr_init "(3), "nerr_match "(3), "nerr_log_error "(3), "nerr_ignore "(3), "nerr_register "(3), "nerr_handle clearsilver-0.10.5/man/man3/hdf_set_symlink.30000644001211700116100000000364610645505100015710 00000000000000.TH hdf_set_symlink 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_symlink - Set part of the tree to link to another .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *hdf_set_symlink (HDF *hdf, const char *src, const char *dest); .Se .SH ARGUMENTS hdf -> the dataset node .br src -> the source node name .br dest -> the destination node name (from the top of the .br dataset, not relative names) .SH DESCRIPTION hdf_set_symlink creates a link between two sections of an HDF dataset. The link is "by name" hence the term "symlink". This means that the destination node does not need to exist. Any attempt to access the source node will cause the function to walk to the dest node, and then continue walking from there. Using symlinks can "hide" values in the dataset since you won't be able to access any children of the linked node directly, though dumps and other things which access the data structure directly will bypass the symlink. Use this feature sparingly as its likely to surprise you. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_valuef.30000644001211700116100000000312610645505100015461 00000000000000.TH hdf_get_valuef 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_valuef - Return the value of a node in the data set .SH SYNOPSIS .Ss #include .Se .Ss char* hdf_get_valuef (HDF *hdf, const char *namefmt, ...) ATTRIBUTE_PRINTF(2,3); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br namefmt -> the printf-style format string .br ... -> arguments to fill out namefmt .SH DESCRIPTION hdf_get_valuef walks the data set pointed to by hdf via namefmt printf expanded with varargs, and returns the string value located there, or NULL if it doesn't exist. This differs from hdf_get_value in that there is no default value possible. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_dump_str.30000644001211700116100000000225010645505100015172 00000000000000.TH hdf_dump_str 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_dump_str - dump an HDF dataset to STRING Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_dump_str(HDF *hdf, const char *prefix, int compact, STRING *str); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_int_value.30000644001211700116100000000312210645505100016161 00000000000000.TH hdf_get_int_value 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_int_value - Return the integer value of a point in the data set .SH SYNOPSIS .Ss #include .Se .Ss int hdf_get_int_value (HDF *hdf, const char *name, int defval); .Se .SH ARGUMENTS hdf -> a node in an HDF data set .br name -> the name of a node to walk to in the data set .br defval -> value to return in case of error or if the node .br doesn't exist .SH DESCRIPTION hdf_get_int_value walks the HDF data set pointed to by hdf to name, and returns the value of that node converted to an integer. If that node does not exist, or it does not contain a number, the defval is returned. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_read_string_ignore.30000644001211700116100000000226210645505100017204 00000000000000.TH hdf_read_string_ignore 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_read_string_ignore - Read an HDF string and ignore errors Description: Input: Output: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_read_string_ignore (HDF *hdf, const char *s, int ignore); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_copy.30000644001211700116100000000267410645505100014321 00000000000000.TH hdf_copy 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_copy - copy part of an HDF dataset to another .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_copy (HDF *dest_hdf, const char *name, HDF *src); .Se .SH ARGUMENTS dest_hdf -> the destination dataset .br name -> the name of the destination node .br src -> the hdf dataset to copy to the destination .SH DESCRIPTION hdf_copy is a deep copy of an HDF tree pointed to by src to the named node of dest. dest and src need not be part of the same data set .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_node.30000644001211700116100000000303510645505100015123 00000000000000.TH hdf_get_node 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_node - Similar to hdf_get_obj except all the nodes are created if the don't exist. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR * hdf_get_node (HDF *hdf, const char *name, HDF **ret); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br name -> the name to walk to .SH DESCRIPTION hdf_get_node is similar to hdf_get_obj, except instead of stopping if it can't find a node in the tree, it will create all of the nodes necessary to hand you back the node you ask for. Nodes are created with no value. .SH "RETURN VALUE" ret -> the dataset node you asked for .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_set_value.30000644001211700116100000000334210645505100015327 00000000000000.TH hdf_set_value 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_value - Set the value of a named node .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_set_value (HDF *hdf, const char *name, const char *value); .Se .SH ARGUMENTS hdf -> the pointer to the hdf dataset .br name -> the named node to walk to .br value -> the value to set the node to .SH DESCRIPTION hdf_set_value will set the value of a named node. All of the interstitial nodes which don't exist will be created with a value of NULL. Existing nodes are not modified. New nodes are created at the end of the list. If a list of nodes exceeds FORCE_HASH_AT, then a HASH will be created at that level and all of the nodes will be added to the hash for faster lookup times. The copy of the value will be made which the dataset will own. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_obj_child.30000644001211700116100000000264110645505100015256 00000000000000.TH hdf_obj_child 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_obj_child - Return the first child of a dataset node .SH SYNOPSIS .Ss #include .Se .Ss HDF* hdf_obj_child (HDF *hdf); .Se .SH ARGUMENTS hdf -> the hdf dataset node .SH DESCRIPTION hdf_obj_child and the other hdf_obj_ functions are accessors to the HDF dataset. Although we do not currently "hide" the HDF struct implementation, we recommend you use the accessor functions instead of accessing the values directly. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_read_string.30000644001211700116100000000217710645505100015646 00000000000000.TH hdf_read_string 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_read_string - read an HDF string Description: Input: Output: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_read_string (HDF *hdf, const char *s); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_set_buf.30000644001211700116100000000300210645505100014760 00000000000000.TH hdf_set_buf 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_buf - Set the value of a node without duplicating the value .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_set_buf (HDF *hdf, const char *name, char *value); .Se .SH ARGUMENTS hdf -> the hdf dataset node .br name -> the name to walk to .br value -> the malloc'd value .SH DESCRIPTION hdf_set_buf is similar to hdf_set_value, except the dataset takes ownership of the value instead of making a copy of it. The dataset assumes that value was malloc'd, since it will attempt to free it when hdf_destroy is called .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_register_fileload.30000644001211700116100000000332510645505100017024 00000000000000.TH hdf_register_fileload 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_register_fileload - register a fileload function .SH SYNOPSIS .Ss #include .Se .Ss void hdf_register_fileload(HDF *hdf, void *ctx, HDFFILELOAD fileload); .Se .SH ARGUMENTS hdf - pointer to a head HDF node .br ctx - pointer that is passed to the HDFFILELOAD function when called .br fileload - a HDFFILELOAD function .SH DESCRIPTION hdf_register_fileload registers a fileload function that overrides the built-in function. The built-in function uses hdf_search_path and ne_file_load (based on stat/open/read) to find and load the file on every hdf_read_file (including #include). You can override this function if you wish to provide other file search functions, or load the hdf file from an in-memory cache, etc. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_obj.30000644001211700116100000000254110645505100014751 00000000000000.TH hdf_get_obj 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_obj - return the HDF data set node at a named location .SH SYNOPSIS .Ss #include .Se .Ss HDF* hdf_get_obj (HDF *hdf, const char *name); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br name -> the name to walk to .SH DESCRIPTION hdf_get_obj walks the dataset given by hdf to the node named name, and then returns the pointer to that node .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_attr.30000644001211700116100000000216110645505100015147 00000000000000.TH hdf_get_attr 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_attr - Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss HDF_ATTR* hdf_get_attr (HDF *hdf, const char *name); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_obj_top.30000644001211700116100000000270710645505100015000 00000000000000.TH hdf_obj_top 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_obj_top - Return the pointer to the top dataset node .SH SYNOPSIS .Ss #include .Se .Ss HDF* hdf_obj_top (HDF *hdf); .Se .SH ARGUMENTS hdf -> the hdf dataset node .SH DESCRIPTION hdf_obj_top is an accessor function which returns a pointer to the top of the dataset, the node which was returned by hdf_init. This is most useful for implementations of language wrappers where individual nodes are tied garbage colletion wise to the top node of the data set .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_dump_format.30000644001211700116100000000223110645505100015651 00000000000000.TH hdf_dump_format 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_dump_format - dump an HDF dataset to FILE *fp Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_dump_format (HDF *hdf, int lvl, FILE *fp); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_destroy.30000644001211700116100000000276110645505100015035 00000000000000.TH hdf_destroy 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_destroy - deallocate an HDF data set .SH SYNOPSIS .Ss #include .Se .Ss void hdf_destroy (HDF **hdf); .Se .SH ARGUMENTS hdf - pointer to an HDF data set allocated with hdf_init .SH DESCRIPTION hdf_destroy is used to deallocate all memory associated with an hdf data set. Although you can pass an HDF node as an argument to this function, you are likely to cause a segfault if you continue to access the data set. In the future, we may restrict hdf_destroy so it only works on the top level node. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_init.30000644001211700116100000000242410645505100014303 00000000000000.TH hdf_init 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_init - Initialize an HDF data set .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_init (HDF **hdf); .Se .SH ARGUMENTS hdf - pointer to an HDF pointer .SH DESCRIPTION hdf_init initializes an HDF data set and returns the pointer to the top node in the data set. .SH "RETURN VALUE" hdf - allocated hdf node .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_obj_value.30000644001211700116100000000256610645505100015315 00000000000000.TH hdf_obj_value 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_obj_value - Return the value of a node .SH SYNOPSIS .Ss #include .Se .Ss char* hdf_obj_value (HDF *hdf); .Se .SH ARGUMENTS hdf -> the hdf dataset node .SH DESCRIPTION hdf_obj_value is an accessor function for a dataset node which returns the value of the node, or NULL if the node has no value. This is not a copy of the value, so the node retains ownership of the value .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_write_string.30000644001211700116100000000221710645505100016060 00000000000000.TH hdf_write_string 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_write_string - serialize an HDF dataset to a string Description: Input: Output: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_write_string (HDF *hdf, char **s); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_sort_obj.30000644001211700116100000000373210645505100015164 00000000000000.TH hdf_sort_obj 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_sort_obj - sort the children of an HDF node .SH SYNOPSIS .Ss #include .Se .Ss hdf_sort_obj() .Se .SH ARGUMENTS h - HDF node .br compareFunc - function which returns 1,0,-1 depending on some .br criteria. The arguments to this sort function .br are pointers to pointers to HDF elements. For .br example: .br int sortByName(const void *a, const void *b) { .br HDF **ha = (HDF **)a; .br HDF **hb = (HDF **)b; .br * .br return strcasecmp(hdf_obj_name(*ha), hdf_obj_name(*hb)); .br } .br * .SH DESCRIPTION hdf_sort_obj will sort the children of an HDF node, based on the given comparison function. This function works by creating an array of the pointers for each child object of h, using qsort to sort that array, and then re-ordering the linked list of children to the new order. The qsort compare function uses a pointer to the value in the array, which in our case is a pointer to an HDF struct, so your comparison function should work on HDF ** pointers. .SH "RETURN VALUE" None (h children will be sorted) .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_write_file_atomic.30000644001211700116100000000253510645505100017030 00000000000000.TH hdf_write_file_atomic 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_write_file_atomic - write an HDF data file atomically .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_write_file_atomic (HDF *hdf, const char *path); .Se .SH DESCRIPTION hdf_write_file_atomic is similar to hdf_write_file, except the new file is created with a unique name and then rename(2) is used to atomically replace the old file with the new file Input: Output: .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_obj_attr.30000644001211700116100000000220410645505100015140 00000000000000.TH hdf_obj_attr 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_obj_attr - Return the HDF Attributes for a node Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss HDF_ATTR* hdf_obj_attr (HDF *hdf); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_set_valuef.30000644001211700116100000000400110645505100015466 00000000000000.TH hdf_set_valuef 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_valuef - Set the value of a named node .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_set_valuef (HDF *hdf, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); .Se .SH ARGUMENTS hdf -> the pointer to the hdf dataset .br fmt -> the name=value printf(3) format string .SH DESCRIPTION hdf_set_valuef is a convenience function that wraps hdf_set_value. Due to limitations of C, the fmt is in the format "name=value", where we will first format the entire string, and then break it at the first (from the left) equal sign (=) and use the left portion as the name and the right portion as the value. This function is somewhat inefficient in that it first allocates the full name=value, and then the call to hdf_set_value duplicates the value portion, and then we free the name=value. Currently, we don't strip whitespace from the key or value. In the future, this function might work more like reading a single line of an HDF string or file, allowing for attributes and symlinks to be specified... maybe. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_copy.30000644001211700116100000000310110645505100015142 00000000000000.TH hdf_get_copy 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_copy - Returns a copy of a string in the HDF data set .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_get_copy (HDF *hdf, const char *name, char **value, const char *defval); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br name -> the name to walk the data set to .br defval -> the default value to return if the node doesn't .br exist .SH DESCRIPTION hdf_get_copy is similar to hdf_get_value, except that it returns an malloc'd copy of the string. .SH "RETURN VALUE" value -> the allocated string (if defval = NULL, then value .br will be NULL if defval is used) .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_write_file.30000644001211700116100000000220310645505100015464 00000000000000.TH hdf_write_file 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_write_file - write an HDF data file Description: Input: Output: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_write_file (HDF *hdf, const char *path); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_valuevf.30000644001211700116100000000303710645505100015650 00000000000000.TH hdf_get_valuevf 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_valuevf - Return the value of a node in the data set .SH SYNOPSIS .Ss #include .Se .Ss char* hdf_get_valuevf (HDF *hdf, const char *namefmt, va_list ap); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br namefmt -> the format string .br ap -> va_list of varargs .SH DESCRIPTION hdf_get_valuevf walks the data set pointed to by hdf via namefmt printf expanded with varargs ap, and returns the string value located there, or NULL if it doesn't exist. This differs from hdf_get_value in that there is no default value possible. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_set_int_value.30000644001211700116100000000266410645505100016207 00000000000000.TH hdf_set_int_value 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_int_value - Set the value of a named node to a number .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_set_int_value (HDF *hdf, const char *name, int value); .Se .SH ARGUMENTS hdf -> the pointer to the hdf dataset .br name -> the named node to walk to .br value -> the value to set the node to .SH DESCRIPTION hdf_set_int_value is a helper function that maps an integer to a string, and then calls hdf_set_value with that string .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_dump.30000644001211700116100000000220310645505100014300 00000000000000.TH hdf_dump 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_dump - dump an HDF dataset to stdout Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_dump (HDF *hdf, const char *prefix); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_value.30000644001211700116100000000275210645505100015317 00000000000000.TH hdf_get_value 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_value - Return the value of a node in the data set .SH SYNOPSIS .Ss #include .Se .Ss char *hdf_get_value (HDF *hdf, const char *name, const char *defval); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br name -> the name to walk the data set to .br defval -> the default value to return if the node doesn't .br exist .SH DESCRIPTION hdf_get_value walks the data set pointed to by hdf via name and returns the string value located there, or defval if the node doesn't exist .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_set_copy.30000644001211700116100000000275610645505100015175 00000000000000.TH hdf_set_copy 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_copy -> Copy a value from one location in the dataset to another .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_set_copy (HDF *hdf, const char *dest, const char *src); .Se .SH ARGUMENTS hdf -> the pointer to the dataset node .br dest -> the name of the destination node .br src -> the name of the source node .SH DESCRIPTION hdf_set_copy first walks the hdf dataset to the named src node, and then copies that value to the named dest node. If the src node is not found, an error is raised. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_obj_next.30000644001211700116100000000235210645505100015150 00000000000000.TH hdf_obj_next 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_obj_next - Return the next node of a dataset level .SH SYNOPSIS .Ss #include .Se .Ss HDF* hdf_obj_next (HDF *hdf); .Se .SH ARGUMENTS hdf -> the hdf dataset node .SH DESCRIPTION hdf_obj_next is an accessor function for the HDF struct .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_search_path.30000644001211700116100000000277010645505100015625 00000000000000.TH hdf_search_path 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_search_path - Find a file given a search path in HDF .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_search_path (HDF *hdf, const char *path, char *full); .Se .SH ARGUMENTS hdf -> the hdf dataset to use .br path -> the relative path .br full -> a pointer to a _POSIX_PATH_MAX buffer .SH DESCRIPTION hdf_search_path is a convenience/utility function that searches for relative filenames in a search path. The search path is the list given by the children of hdf.loadpaths. .SH "RETURN VALUE" full -> the full path of the file .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_obj_name.30000644001211700116100000000246510645505100015117 00000000000000.TH hdf_obj_name 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_obj_name - Return the name of a node .SH SYNOPSIS .Ss #include .Se .Ss char* hdf_obj_name (HDF *hdf); .Se .SH ARGUMENTS hdf -> the hdf dataset node .SH DESCRIPTION hdf_obj_name is an accessor function for a datset node which returns the name of the node. This is just the local name, and not the full path. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_set_attr.30000644001211700116100000000225110645505100015163 00000000000000.TH hdf_set_attr 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_set_attr - Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_set_attr (HDF *hdf, const char *name, const char *key, const char *value); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_get_child.30000644001211700116100000000252710645505100015266 00000000000000.TH hdf_get_child 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_get_child - return the first child of the named node .SH SYNOPSIS .Ss #include .Se .Ss HDF* hdf_get_child (HDF *hdf, const char *name); .Se .SH ARGUMENTS hdf -> the dataset node to start from .br name -> the name to walk to .SH DESCRIPTION hdf_get_child will walk the dataset starting at hdf to name, and return the first child of that node .SH "RETURN VALUE" None .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/hdf_remove_tree.30000644001211700116100000000223310645505100015652 00000000000000.TH hdf_remove_tree 3 "12 July 2007" "ClearSilver" "util/neo_hdf.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME hdf_remove_tree - delete a subtree of an HDF dataset Description: Input: Output: Returns: .SH SYNOPSIS .Ss #include .Se .Ss NEOERR* hdf_remove_tree (HDF *hdf, const char *name); .Se .SH "SEE ALSO" .BR hdf_set_symlink "(3), "hdf_get_valuef "(3), "compareFunc) "(3), "hdf_dump_str "(3), "hdf_get_int_value "(3), "hdf_read_string_ignore "(3), "hdf_copy "(3), "hdf_get_node "(3), "hdf_set_value "(3), "hdf_obj_child "(3), "hdf_read_string "(3), "hdf_set_buf "(3), "hdf_register_fileload "(3), "hdf_get_obj "(3), "hdf_get_attr "(3), "hdf_obj_top "(3), "hdf_dump_format "(3), "hdf_destroy "(3), "hdf_init "(3), "hdf_obj_value "(3), "hdf_write_string "(3), "hdf_set_valuevf "(3), "hdf_sort_obj "(3), "hdf_write_file_atomic "(3), "hdf_obj_attr "(3), "hdf_set_valuef "(3), "hdf_get_copy "(3), "hdf_write_file "(3), "hdf_get_valuevf "(3), "hdf_set_int_value "(3), "hdf_dump "(3), "hdf_get_value "(3), "hdf_set_copy "(3), "hdf_obj_next "(3), "hdf_search_path "(3), "hdf_obj_name "(3), "hdf_set_attr "(3), "hdf_get_child "(3), "hdf_remove_tree clearsilver-0.10.5/man/man3/skipDelete.30000644001211700116100000000115310645505100014606 00000000000000.TH skipDelete 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipDelete - delete an item. .SH SYNOPSIS .Ss #include .Se .Ss void skipDelete(skipList list, UINT32 key); .Se .SH ARGUMENTS list - list to delete item from. .br key - key identifying value to delete. .SH DESCRIPTION Delete the item associated with from . MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/skipFreeList.30000644001211700116100000000107510645505100015124 00000000000000.TH skipFreeList 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipFreeList - free a skip list. .SH SYNOPSIS .Ss #include .Se .Ss void skipFreeList(skipList list); .Se .SH ARGUMENTS list - list to free. .SH DESCRIPTION Release all resources used by including all key/value pairs. MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/skipRelease.30000644001211700116100000000133310645505100014764 00000000000000.TH skipRelease 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipRelease - release lock on value. .SH SYNOPSIS .Ss #include .Se .Ss void skipRelease(skipList list, void *lock); .Se .SH ARGUMENTS list - list containing value to release. .br lock - lock to release. .SH DESCRIPTION Releases the lock on the value associated with . Once the lock is released, the freeValue callback can be called and the item freed (see skipNewList()). MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/skipInsert.30000644001211700116100000000151010645505100014645 00000000000000.TH skipInsert 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipInsert - insert an item. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *skipInsert(skipList list, UINT32 key, void *value, int allowUpdate); .Se .SH ARGUMENTS list - list to add pair to. .br key - key identifying . .br value - value to store (may NOT be NULL) .SH DESCRIPTION Inserts the / pair into the . Key values 0 and -1 are reserved (and illegal). If key is already in list, and is true, value is updated, otherwise SKIPERR_EXISTS is returned. MT-Level: Safe if thread-safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/skipSearch.30000644001211700116100000000164110645505100014613 00000000000000.TH skipSearch 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipSearch - search a skip list. .SH SYNOPSIS .Ss #include .Se .Ss void *skipSearch(skipList list, UINT32 key, void **plock); .Se .SH ARGUMENTS list - list to search in. .br key - key to look for. .br plock - place for value lock (or NULL). .SH DESCRIPTION Searches for in , and returns value if found, or NULL if not. If is non-NULL, then the lock returned in will be associated with the returned value. Until this lock is passed to skipRelease(), the value will not be freed with the freeValue callback (see skipNewList()). MT-Level: Safe if thread-safe. .SH "RETURN VALUE" plock - set to value lock. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/skipNext.30000644001211700116100000000177610645505100014335 00000000000000.TH skipNext 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipNext - find next item. .SH SYNOPSIS .Ss #include .Se .Ss void *skipNext(skipList list, UINT32 *pkey, void **plock); .Se .SH ARGUMENTS list - list to search in. .br pkey - pointer to previous key (0 to start). .br plock - place for value lock (or NULL). .SH DESCRIPTION Searches in list for item with key next larger that the one in , and returns its value if found, or NULL if not. If is non-NULL, then the lock returned in will be associated with the returned value. Until this lock is passed to skipRelease(), the value will not be freed with the freeValue callback (see skipNewList()). MT-Level: Safe if thread-safe. .SH "RETURN VALUE" pkey - set to new key. .br plock - set to value lock. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/skipNewList.30000644001211700116100000000241710645505100014775 00000000000000.TH skipNewList 3 "12 July 2007" "ClearSilver" "util/skiplist.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME skipNewList - create a skip list. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *skipNewList(skipList *skip, int threaded, int root, int maxLevel, int flushLimit, skipFreeValue freeValue, void *ctx); .Se .SH ARGUMENTS threaded - true if list should be thread-safe. .br root - performance parameter (see above). .br maxLevel - performance parameter (see above). .br flushLimit - max deleted items to keep cached before .br forcing a flush. .br freeValue - callback made whenever a value is flushed. .br ctx - context to pass to . .SH DESCRIPTION Returns a new skip list. If is true, list is multi-thread safe. and determine performance and expected size (see discussion above). is for threaded lists and determines the maximum number of deleted items to keep cached during concurrent searches. Once the limit is reached, new concurrent reads are blocked until all deleted items are flushed. MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR skipDelete "(3), "skipFreeList "(3), "skipRelease "(3), "skipInsert "(3), "skipSearch "(3), "skipNext "(3), "skipNewList clearsilver-0.10.5/man/man3/mCreate.30000644001211700116100000000115410645505100014076 00000000000000.TH mCreate 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME mCreate - initialize a mutex. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *mCreate(pthread_mutex_t *mutex); .Se .SH ARGUMENTS mutex - mutex to initialize. .SH DESCRIPTION Initializes the mutex . MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/fCreate.30000644001211700116100000000131110645505100014062 00000000000000.TH fCreate 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME fCreate - create a file lock. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *fCreate(int *plock, const char *file); .Se .SH ARGUMENTS plock - place for lock. .br file - path of file to use as lock. .SH DESCRIPTION Creates a file lock on named file . The lock is returned in . MT-Level: Safe. .SH "RETURN VALUE" plock - set to lock identifier. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/mUnlock.30000644001211700116100000000111510645505100014123 00000000000000.TH mUnlock 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME mUnlock - unlock a mutex. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *mUnlock(pthread_mutex_t *mutex); .Se .SH ARGUMENTS mutex - mutex to unlock. .SH DESCRIPTION Unlocks the mutex . MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/fUnlock.30000644001211700116100000000111310645505100014112 00000000000000.TH fUnlock 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME fUnlock - release file lock. .SH SYNOPSIS .Ss #include .Se .Ss void fUnlock(int lock); .Se .SH ARGUMENTS lock - Lock to release. .SH DESCRIPTION Releases the lock identified by . MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/cBroadcast.30000644001211700116100000000125510645505100014565 00000000000000.TH cBroadcast 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cBroadcast - broadcast signal to all waiting threads. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cBroadcast(pthread_cond_t *cond); .Se .SH ARGUMENTS cond - condition variable to broadcast on. .SH DESCRIPTION Broadcasts a signal to all threads waiting on condition variable . MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/cSignal.30000644001211700116100000000123210645505100014073 00000000000000.TH cSignal 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cSignal - send signal to one waiting thread. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cSignal(pthread_cond_t *cond); .Se .SH ARGUMENTS cond - condition variable to send signal on. .SH DESCRIPTION Sends a signal to one thread waiting on condition variable . MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/fFind.30000644001211700116100000000137410645505100013550 00000000000000.TH fFind 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME fFind - find a file lock. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *fFind(int *plock, const char *file); .Se .SH ARGUMENTS plock - place for lock. .br file - path of file to use as lock. .SH DESCRIPTION Find a file identified by the path , and returns a lock identifier for it in . If the file doesn't exist, returns true. MT-Level: Safe. .SH "RETURN VALUE" plock - set to lock identifier. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/cDestroy.30000644001211700116100000000125010645505100014307 00000000000000.TH cDestroy 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cDestroy - destroy a condition variable. .SH SYNOPSIS .Ss #include .Se .Ss void cDestroy(pthread_cond_t *cond); .Se .SH ARGUMENTS cond - condition variable to destroy. .SH DESCRIPTION Destroys the condition variable that was initialized by cCreate(). MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/cCreate.30000644001211700116100000000121610645505100014063 00000000000000.TH cCreate 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cCreate - initialize a condition variable. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cCreate(pthread_cond_t *cond); .Se .SH ARGUMENTS cond - condition variable to initialize. .SH DESCRIPTION Initializes the condition variable . MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/mDestroy.30000644001211700116100000000120510645505100014321 00000000000000.TH mDestroy 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME mDestroy - destroy a mutex. .SH SYNOPSIS .Ss #include .Se .Ss void mDestroy(pthread_mutex_t *mutex); .Se .SH ARGUMENTS mutex - mutex to destroy. .SH DESCRIPTION Destroys the mutex that was initialized by mCreate(). MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/cWait.30000644001211700116100000000135610645505100013571 00000000000000.TH cWait 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cWait - wait a condition variable signal. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cWait(pthread_cond_t *cond, pthread_mutex_t *mutex); .Se .SH ARGUMENTS cond - condition variable to wait on. .br mutex - locked mutex to protect . .SH DESCRIPTION Waits for a signal on condition variable . The mutex must be locked by the thread. MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/fLock.30000644001211700116100000000116610645505100013557 00000000000000.TH fLock 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME fLock - acquire file lock. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *fLock(int lock); .Se .SH ARGUMENTS lock - Lock to acquire. .SH DESCRIPTION Acquires the lock identified by . This call blocks until the lock is acquired. MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/fDestroy.30000644001211700116100000000117010645505100014313 00000000000000.TH fDestroy 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME fDestroy - destroy a lock. .SH SYNOPSIS .Ss #include .Se .Ss void fDestroy(int lock); .Se .SH ARGUMENTS lock - Lock to destroy. .SH DESCRIPTION Destroys the lock that was created by fCreate() or fFind(). MT-Level: Safe for unique . .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/mLock.30000644001211700116100000000116010645505100013560 00000000000000.TH mLock 3 "12 July 2007" "ClearSilver" "util/ulocks.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME mLock - lock a mutex. .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *mLock(pthread_mutex_t *mutex); .Se .SH ARGUMENTS mutex - mutex to lock. .SH DESCRIPTION Locks the mutex . This call blocks until the mutex is acquired. MT-Level: Safe. .SH "RETURN VALUE" None. .SH "SEE ALSO" .BR mCreate "(3), "fCreate "(3), "mUnlock "(3), "fUnlock "(3), "cBroadcast "(3), "cSignal "(3), "fFind "(3), "cDestroy "(3), "cCreate "(3), "mDestroy "(3), "cWait "(3), "fLock "(3), "fDestroy "(3), "mLock clearsilver-0.10.5/man/man3/wdb_keys.30000644001211700116100000000206010645505100014322 00000000000000.TH wdb_keys 3 "12 July 2007" "ClearSilver" "util/wdb.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME wdb_keys .SH SYNOPSIS .Ss #include .Se .Ss NEOERR * wdb_keys (WDB *wdb, char **primary_key, ULIST **data); .Se .SH ARGUMENTS wdb - open database .SH DESCRIPTION this function returns the key and column names for the current database .SH "RETURN VALUE" primary_key - pointer to the primary key .br data - pointer to a ULIST of the columns. .br both of these are allocated structures, you can clear data .br with uListDestroy (data, ULIST_FREE) .SH "SEE ALSO" .BR wdb_destroy "(3), "wdbr_delete "(3), "wdb_update "(3), "wdbr_dump "(3), "wdb_save "(3), "wdbr_create "(3), "wdbr_destroy "(3), "wdb_attr_set "(3), "wdb_attr_next "(3), "wdb_open "(3), "wdb_column_exchange "(3), "wdbr_set "(3), "wdb_column_insert "(3), "wdbr_save "(3), "wdbr_next "(3), "wdb_keys "(3), "wdb_column_delete "(3), "wdbc_create "(3), "wdbr_get "(3), "wdb_attr_get "(3), "wdbr_find "(3), "wdbr_lookup "(3), "wdb_create "(3), "wdbc_destroy "(3), "wdb_column_update clearsilver-0.10.5/man/man3/cs_dump.30000644001211700116100000000161410645505100014151 00000000000000.TH cs_dump 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_dump - dump the cs parse tree .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_dump (CSPARSE *parse, void *ctx, CSOUTFUNC cb); .Se .SH ARGUMENTS parse - the CSPARSE structure created with cs_init .br ctx - user data to be passed to the CSOUTFUNC .br cb - a CSOUTFUNC callback .SH DESCRIPTION cs_dump will dump the CS parse tree in the parse struct. This can be useful for debugging your templates. This function also uses the CSOUTFUNC callback to display the parse tree. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_destroy.30000644001211700116100000000177110645505100014701 00000000000000.TH cs_destroy 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_destroy - clean up and dealloc a parse tree .SH SYNOPSIS .Ss #include .Se .Ss void cs_destroy (CSPARSE **parse); .Se .SH ARGUMENTS parse - a pointer to a parse structure. .SH DESCRIPTION cs_destroy will clean up all the memory associated with a CSPARSE structure, including strings passed to cs_parse_string. This does not clean up any memory allocated by your own CSOUTFUNC or the HDF data structure passed to cs_init. It is safe to call this with a NULL pointer, and it will leave parse NULL as well (ie, it can be called more than once on the same var) .SH "RETURN VALUE" parse - will be NULL .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_render.30000644001211700116100000000236310645505100014465 00000000000000.TH cs_render 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_render - render a CS parse tree .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_render (CSPARSE *parse, void *ctx, CSOUTFUNC cb); .Se .SH ARGUMENTS parse - the CSPARSE structure containing the CS parse tree .br that will be evaluated .br ctx - user data that will be passed as the first variable to .br the CSOUTFUNC. .br cb - a CSOUTFUNC called to render the output. A CSOUTFUNC is .br defined as: .br typedef NEOERR* (*CSOUTFUNC)(void *, char *); .SH DESCRIPTION cs_render will evaluate a CS parse tree, calling the CSOUTFUNC passed to it for output. Note that calling cs_render multiple times on the same parse tree may or may not render the same output as the set statement has side-effects, it updates the HDF data used by the render. Typically, you will call one of the cs_parse functions before calling this function. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_register_esc_strfunc.30000644001211700116100000000206010645505100017422 00000000000000.TH cs_register_esc_strfunc 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_register_esc_strfunc - cs_register_strfunc with escaping context .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_register_esc_strfunc(CSPARSE *parse, char *funcname, CSSTRFUNC str_func); .Se .SH ARGUMENTS parse - a pointer to a CSPARSE structure initialized with cs_init() .br funcname - the name for the CS function call .br Note that registering a duplicate funcname will .br raise a NERR_DUPLICATE error .br str_func - a CSSTRFUNC not-callback .SH DESCRIPTION cs_register_esc_strfunc functions exactly as cs_register_strfunc except that it changes the evaluation escaping context to disable default escaping. .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_register_fileload.30000644001211700116100000000236610645505100016674 00000000000000.TH cs_register_fileload 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_register_fileload - register a fileload function .SH SYNOPSIS .Ss #include .Se .Ss void cs_register_fileload(CSPARSE *parse, void *ctx, CSFILELOAD fileload); .Se .SH ARGUMENTS parse - a pointer to an initialized CSPARSE structure .br ctx - pointer that is passed to the CSFILELOAD function when called .br fileload - a CSFILELOAD function .SH DESCRIPTION cs_register_fileload registers a fileload function that overrides the built-in function. The built-in function uses hdf_search_path and ne_file_load (based on stat/open/read) to find and load the file on every template render. You can override this function if you wish to provide other template search functions, or load the template from an in-memory cache, etc. This fileload function will be used by cs_parse, including include: commands in the template. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_init.30000644001211700116100000000224310645505100014146 00000000000000.TH cs_init 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_init - create and initialize a CS context .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_init (CSPARSE **parse, HDF *hdf); .Se .SH ARGUMENTS parse - a pointer to a pointer to a CSPARSE structure that .br will be created .br hdf - the HDF dataset to be used during parsing and rendering .SH DESCRIPTION cs_init will create a CSPARSE structure and initialize it. This structure maintains the state and information necessary for parsing and rendering a CS template. MT-Level: cs routines perform no locking, and neither do hdf routines. They should be safe in an MT environment as long as they are confined to a single thread. .SH "RETURN VALUE" parse will contain a pointer to the allocated CSPARSE .br structure. This structure will be deallocated with .br cs_destroy() .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_register_strfunc.30000644001211700116100000000301210645505100016566 00000000000000.TH cs_register_strfunc 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_register_strfunc - register a string handling function .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_register_strfunc(CSPARSE *parse, char *funcname, CSSTRFUNC str_func); .Se .SH ARGUMENTS parse - a pointer to a CSPARSE structure initialized with cs_init() .br funcname - the name for the CS function call .br Note that registering a duplicate funcname will .br raise a NERR_DUPLICATE error .br str_func - a CSSTRFUNC not-callback .SH DESCRIPTION cs_register_strfunc will register a string function that can be called during CS render. This not-callback is designed to allow for string formating/escaping functions that are not built-in to CS (since CS is not HTML specific, for instance, but it is very useful to have CS have functions for javascript/html/url escaping). Note that we explicitly don't provide any associated data or anything to attempt to keep you from using this as a generic callback... The format of a CSSTRFUNC is: NEOERR * str_func(char *in, char **out); This function should not modify the input string, and should allocate the output string with a libc function. (as we will call free on it) .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_parse_string.30000644001211700116100000000226110645505100015703 00000000000000.TH cs_parse_string 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_parse_string - parse a CS template string .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_parse_string (CSPARSE *parse, char *buf, size_t blen); .Se .SH ARGUMENTS parse - a CSPARSE structure created with cs_init .br buf - the string to parse. Embedded NULLs are not currently .br supported .br blen - the length of the string .SH DESCRIPTION cs_parse_string parses a string. The string is modified, and internal references are kept by the parse tree. For this reason, ownership of the string is transfered to the CS system, and the string will be free'd when cs_destroy() is called. The parse information will be appended to the current parse tree. During parse, the only HDF variables which are evaluated are those used in evar or include statements. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cs_parse_file.30000644001211700116100000000173010645505100015314 00000000000000.TH cs_parse_file 3 "12 July 2007" "ClearSilver" "cs/cs.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cs_parse_file - parse a CS template file .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cs_parse_file (CSPARSE *parse, const char *path); .Se .SH ARGUMENTS parse - a CSPARSE structure created with cs_init .br path - the path to the file to parse .SH DESCRIPTION cs_parse_file will parse the CS template located at path. It will use hdf_search_path() if path does not begin with a '/'. The parsed CS template will be appended to the current parse tree stored in the CSPARSE structure. The entire file is loaded into memory and parsed in place. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cs_dump "(3), "cs_destroy "(3), "cs_render "(3), "cs_register_esc_strfunc "(3), "cs_arg_parsev "(3), "cs_register_fileload "(3), "cs_init "(3), "cs_register_strfunc "(3), "cs_arg_parse "(3), "cs_parse_string "(3), "cs_parse_file "(3), "= "(3), "cs_register_function clearsilver-0.10.5/man/man3/cgi_debug_init.30000644001211700116100000000254110645505100015452 00000000000000.TH cgi_debug_init 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_debug_init - initialize standalone debugging .SH SYNOPSIS .Ss #include .Se .Ss void cgi_debug_init (int argc, char **argv); .Se .SH ARGUMENTS argc/argv - the arguments from main .SH DESCRIPTION cgi_debug_init initializes a CGI program for standalone debugging. By running a ClearSilver CGI program with a filename on the command line as the first argument, the CGI program will load that file of the form K=V as a set of HTTP/CGI environment variables. This allows you to run the program under a debugger in a reproducible environment. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_parse.30000644001211700116100000000341010645505100014447 00000000000000.TH cgi_parse 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_parse - Parse incoming CGI data .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_parse (CGI *cgi); .Se .SH ARGUMENTS cgi - a pointer to a CGI pointer .SH DESCRIPTION We split cgi_init into two sections, one that parses just the basics, and the second is cgi_parse. cgi_parse is responsible for parsing the entity body of the HTTP request. This payload is typically only sent (expected) on POST/PUT requests, but generally this is called on all incoming requests. This function walks the list of registered parse callbacks (see cgi_register_parse_cb), and if none of those matches or handles the request, it handlers: POST w/ application/x-www-form-urlencoded POST w/ application/form-data PUT w/ any content type In general, if there is no Content-Length, then cgi_parse ignores the payload and doesn't raise an error. .SH "RETURN VALUE" Either data populated into files and cgi->hdf, or whatever .br other side effects of your own registered callbacks. .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_destroy.30000644001211700116100000000253010645505100015030 00000000000000.TH cgi_destroy 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_destroy - deallocate the data associated with a CGI .SH SYNOPSIS .Ss #include .Se .Ss void cgi_destroy (CGI **cgi); .Se .SH ARGUMENTS cgi - a pointer to a pointer to a CGI struct .SH DESCRIPTION cgi_destroy will destroy all the data associated with a CGI, which mostly means the associated HDF and removal of any files that were uploaded via multipart/form-data. (Note that even in the event of a crash, these files will be deleted, as they were unlinked on creation and only exist because of the open file pointer) .SH "RETURN VALUE" cgi - NULL on output .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_output.30000644001211700116100000000227010645505100014700 00000000000000.TH cgi_output 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_output - display the CGI output to the user .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_output (CGI *cgi, STRING *output); .Se .SH ARGUMENTS cgi - a pointer a CGI struct allocated with cgi_init .br output - the data to send to output from the CGI .SH DESCRIPTION Normally, this is called by cgi_display, but some people wanted it external so they could call it directly. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_url_validate.30000644001211700116100000000251410645505100016014 00000000000000.TH cgi_url_validate 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_url_validate - validate that url is of an allowed format .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_url_validate (const char *buf, char **esc); .Se .SH ARGUMENTS buf - a 0 terminated string .SH DESCRIPTION cgi_url_validate will check that a URL starts with one of the accepted safe schemes. If not, it returns "#" as a safe substitute. Currently accepted schemes are http, https, ftp and mailto. It then html escapes the entire URL so that it is safe to insert in an href attribute. .SH "RETURN VALUE" esc - a newly allocated string .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_cs_init.30000644001211700116100000000232210645505100014766 00000000000000.TH cgi_cs_init 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_cs_init - initialize CS parser with the CGI defaults .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_cs_init(CGI *cgi, CSPARSE **cs); .Se .SH ARGUMENTS cgi - a pointer a CGI struct allocated with cgi_init .br cs - a pointer to a CS struct pointer .SH DESCRIPTION cgi_cs_init initializes a CS parser with the CGI HDF context, and registers the standard CGI filters .SH "RETURN VALUE" cs - the allocated/initialized CS struct .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_url_escape_more.30000644001211700116100000000254010645505100016504 00000000000000.TH cgi_url_escape_more 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_url_escape_more - url escape a string .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_url_escape_more (const char *buf, char **esc, const char *other); .Se .SH ARGUMENTS buf - a 0 terminated string .br other - a 0 terminated string of characters to escape .SH DESCRIPTION cgi_url_escape_more will do URL escaping on the passed in string, and return a newly allocated string that is escaped. Characters which are escaped include control characters, %, ?, +, space, =, &, /, and " and any characters in other .SH "RETURN VALUE" esc - a newly allocated string .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_neo_error.30000644001211700116100000000235510645505100015336 00000000000000.TH cgi_neo_error 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_neo_error - display a NEOERR call backtrace .SH SYNOPSIS .Ss #include .Se .Ss void cgi_neo_error (CGI *cgi, NEOERR *err); .Se .SH ARGUMENTS cgi - a pointer to a CGI struct .br err - a NEOERR (see util/neo_err.h for details) .SH DESCRIPTION cgi_neo_error will output a 500 error containing the NEOERR call backtrace. This function is likely to be removed from future versions in favor of some sort of user error mechanism. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_redirect.30000644001211700116100000000262010645505100015140 00000000000000.TH cgi_redirect 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_redirect - send an HTTP 302 redirect response .SH SYNOPSIS .Ss #include .Se .Ss void cgi_redirect (CGI *cgi, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); .Se .SH ARGUMENTS cgi - cgi struct .br fmt - printf style format with args .SH DESCRIPTION cgi_redirect will redirect the user to another page on your site. This version takes only the path portion of the URL. As with all printf style commands, you should not call this with arbitrary input that may contain % characters, if you are forwarding something directly, use a format like cgi_redirect (cgi, "%s", buf) .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_filehandle.30000644001211700116100000000261510645505100015436 00000000000000.TH cgi_filehandle 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_filehandle - return a file pointer to an uploaded file .SH SYNOPSIS .Ss #include .Se .Ss FILE *cgi_filehandle (CGI *cgi, const char *form_name); .Se .SH ARGUMENTS cgi - a pointer to a CGI struct allocated with cgi_init .br form_name - the form name that the file was uploaded as .br (not the filename) (if NULL, we're asking for the .br file handle for the PUT upload) .SH DESCRIPTION cgi_filehandle will return the stdio FILE pointer associated with a file that was uploaded using multipart/form-data. The FILE pointer is positioned at the start of the file when first available. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_register_parse_cb.30000644001211700116100000000557210645505100017032 00000000000000.TH cgi_register_parse_cb 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_register_parse_cb - Register a parse callback .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_register_parse_cb(CGI *cgi, const char *method, const char *ctype, void *rock, CGI_PARSE_CB parse_cb); .Se .SH ARGUMENTS cgi - a CGI struct .br method - the HTTP method you want to handle, or * for all .br ctype - the HTTP Content-Type you want to handle, or * for all .br rock - opaque data that we'll pass to your call back .SH DESCRIPTION The ClearSilver CGI Kit has built-in functionality to handle the following methods: GET -> doesn't have any data except query string, which is processed for all methods POST w/ application/x-www-form-urlencoded POST w/ multipart/form-data processed as RFC2388 data into files and HDF (see cgi_filehandle()) PUT (any type) The entire data chunk is stored as a file, with meta data in HDF (similar to single files in RFC2388). The data is accessible via cgi_filehandle with NULL for name. To handle other methods/content types, you have to register your own parse function. This isn't necessary if you aren't expecting any data, and technically HTTP only allows data on PUT/POST requests (and presumably user defined methods). In particular, if you want to implement XML-RPC or SOAP, you'll have to register a callback here to grab the XML data chunk. Usually you'll want to register POST w/ application/xml or POST w/ text/xml (you either need to register both or register POST w/ * and check the ctype yourself, remember to nerr_raise(CGIParseNotHandled) if you aren't handling the POST). In general, your callback should: Find out how much data is available: l = hdf_get_value (cgi->hdf, "CGI.ContentLength", NULL); len = atoi(l); And read/handle all of the data using cgiwrap_read. See the builtin handlers for how this is done. Note that cgiwrap_read is not guarunteed to return all of the data you request (just like fread(3)) since it might be reading of a socket. Sorry. You should be careful when reading the data to watch for short reads (ie, end of file) and cases where the client sends you data ad infinitum. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_url_escape.30000644001211700116100000000234310645505100015463 00000000000000.TH cgi_url_escape 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_url_escape - url escape a string .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_url_escape (const char *buf, char **esc); .Se .SH ARGUMENTS buf - a 0 terminated string .SH DESCRIPTION cgi_url_escape will do URL escaping on the passed in string, and return a newly allocated string that is escaped. Characters which are escaped include control characters, %, ?, +, space, =, &, /, and " .SH "RETURN VALUE" esc - a newly allocated string .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_init.30000644001211700116100000000345710645505100014313 00000000000000.TH cgi_init 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_init - Initialize ClearSilver CGI environment .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_init (CGI **cgi, HDF *hdf); .Se .SH ARGUMENTS cgi - a pointer to a CGI pointer .br hdf_file - the path to an HDF data set file that will also be .br loaded into the dataset. This will likely have to .br a be a full path, as the HDF search paths are not .br yet set up. Certain things, like .SH DESCRIPTION cgi_init initializes the ClearSilver CGI environment, including creating the HDF data set. It will then import the standard CGI environment variables into that dataset, will parse the QUERY_STRING into the data set, and parse the HTTP_COOKIE into the data set. Note that if the var xdisplay is in the form data, cgi_init will attempt to validate the value and launch the configured debugger on the CGI program. These variables have to be specified in the hdf_file pointed to by hdf_file. The default settings do not allow debugger launching for security reasons. .SH "RETURN VALUE" cgi - an allocated CGI struct, including .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_redirect_uri.30000644001211700116100000000266410645505100016027 00000000000000.TH cgi_redirect_uri 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_redirect_uri - send an HTTP 302 redirect response .SH SYNOPSIS .Ss #include .Se .Ss void cgi_redirect_uri (CGI *cgi, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); .Se .SH ARGUMENTS cgi - cgi struct .br fmt - printf style format with args .SH DESCRIPTION cgi_redirect_uri will redirect the user to another page on your site. This version takes the full URL, including protocol/domain/port/path. As with all printf style commands, you should not call this with arbitrary input that may contain % characters, if you are forwarding something directly, use a format like cgi_redirect (cgi, "%s", buf) .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_cookie_clear.30000644001211700116100000000306610645505100015763 00000000000000.TH cgi_cookie_clear 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_cookie_clear - clear browser cookie .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_cookie_clear (CGI *cgi, const char *name, const char *domain, const char *path); .Se .SH ARGUMENTS cgi - a CGI struct .br name - the cookie name to clear .br domain - the domain to clear, NULL for none .br path - the cookie's path .SH DESCRIPTION cgi_cookie_clear will send back a Set-Cookie string that will attempt to stop a browser from continuing to send back a cookie. Note that the cookie has to match in name, domain, and path, and the luck of the Irish has to be with you for this work all the time, but at the least it will make the browser send back a cookie with no value, which the ClearSilver cookie parsing code will ignore. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_url_unescape.30000644001211700116100000000222710645505100016027 00000000000000.TH cgi_url_unescape 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_url_unescape - unescape an url encoded string .SH SYNOPSIS .Ss #include .Se .Ss char *cgi_url_unescape (char *buf); .Se .SH ARGUMENTS buf - a 0 terminated string .SH DESCRIPTION cgi_url_unescape will do URL unescaping on the passed in string. This function modifies the string in place This function will decode any %XX character, and will decode + as space .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_vredirect.30000644001211700116100000000234510645505100015332 00000000000000.TH cgi_vredirect 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_vredirect - send an HTTP 302 redirect response .SH SYNOPSIS .Ss #include .Se .Ss void cgi_vredirect (CGI *cgi, int uri, const char *fmt, va_list ap); .Se .SH ARGUMENTS cgi - cgi struct .br uri - whether the URL is full (1) or path only (0) .br fmt - printf format string .br ap - stdarg va_list .SH DESCRIPTION cgi_vredirect is mostly used internally, but can be used if you need a varargs version of the function. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_display.30000644001211700116100000000242010645505100015002 00000000000000.TH cgi_display 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_display - render and display the CGI output to the user .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_display (CGI *cgi, const char *cs_file); .Se .SH ARGUMENTS cgi - a pointer a CGI struct allocated with cgi_init .br cs_file - a ClearSilver template file .SH DESCRIPTION cgi_display will render the CS template pointed to by cs_file using the CGI's HDF data set, and send the output to the user. Note that the output is actually rendered into memory first. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_error.30000644001211700116100000000240610645505100014472 00000000000000.TH cgi_error 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_error - display an error string to the user .SH SYNOPSIS .Ss #include .Se .Ss void cgi_error (CGI *cgi, const char *fmt, ...) ATTRIBUTE_PRINTF(2,3); .Se .SH ARGUMENTS cgi - a pointer to a CGI struct .br fmt - printf style format string and arguments .SH DESCRIPTION cgi_error will output a 500 error containing the specified error message. This function is likely to be removed from future versions in favor of a user error mechanism. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_cookie_set.30000644001211700116100000000372110645505100015466 00000000000000.TH cgi_cookie_set 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_cookie_set - Set a browser Cookie .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgi_cookie_set (CGI *cgi, const char *name, const char *value, const char *path, const char *domain, const char *time_str, int persistent, int secure); .Se .SH ARGUMENTS cgi - a CGI struct .br name - the name of the cookie .br value - the value to set the cookie to. .br path - optional path for which the cookie is valid. Default .br is / .br domain - optional domain for which the cookie is valid. You .br can use cgi_cookie_authority to determine this .br domain. Default is none, which is interpreted by .br the browser as the sending domain only. .br time_str - expiration time string in the following format .SH DESCRIPTION cgi_cookie_set will issue a Set-Cookie header that should cause a browser to return a cookie when required. Note this function does no escaping of anything, you have to take care of that first. HH:MM: SS GMT. Only used if persistent. Default is one year from time of call. persistent - cookie will be stored by the browser between sessions secure - cookie will only be sent over secure connections .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgi_cookie_authority.30000644001211700116100000000277710645505100016735 00000000000000.TH cgi_cookie_authority 3 "12 July 2007" "ClearSilver" "cgi/cgi.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgi_cookie_authority - determine the cookie authority for a domain .SH SYNOPSIS .Ss #include .Se .Ss char *cgi_cookie_authority (CGI *cgi, const char *host); .Se .SH ARGUMENTS cgi - a CGI struct .br host - optional host to match against. If NULL, the function .br will use the HTTP.Host HDF variable. .SH DESCRIPTION cgi_cookie_authority will walk the CookieAuthority portion of the CGI HDF data set, and return the matching domain if it exists. The purpose of this is so that you set domain specific cookies. For instance, you might have CookieAuthority.0 = neotonic.com In which case, any webserver using a hostname ending in neotonic.com will generate a cookie authority of neotonic.com. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgi_debug_init "(3), "cgi_parse "(3), "cgi_destroy "(3), "cgi_js_escape "(3), "cgi_html_escape_strfunc "(3), "cgi_register_strfuncs "(3), "cgi_output "(3), "parse_rfc2388 "(3), "cgi_url_validate "(3), "open_upload "(3), "cgi_cs_init "(3), "cgi_url_escape_more "(3), "cgi_html_strip_strfunc "(3), "cgi_neo_error "(3), "cgi_redirect "(3), "cgi_filehandle "(3), "cgi_register_parse_cb "(3), "cgi_url_escape "(3), "cgi_init "(3), "cgi_redirect_uri "(3), "cgi_cookie_clear "(3), "cgi_url_unescape "(3), "cgi_vredirect "(3), "cgi_display "(3), "cgi_html_ws_strip "(3), "cgi_error "(3), "cgi_cookie_set "(3), "cgi_text_html_strfunc "(3), "cgi_cookie_authority clearsilver-0.10.5/man/man3/cgiwrap_iterenv.30000644001211700116100000000155010645505100015706 00000000000000.TH cgiwrap_iterenv 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_iterenv - iterater for env vars .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgiwrap_iterenv (int n, char **k, char **v); .Se .SH ARGUMENTS n - variable to return. This should start at 0 and increment .br until you receive a NULL return value. .SH DESCRIPTION cgiwrap_iterenv allows a program to iterate over all the environment variables. This is probably mostly used by the default debug output. .SH "RETURN VALUE" k - a malloc'd copy of the variable name .br v - a malloc'd copy of the variable value .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_putenv.30000644001211700116100000000171510645505100015556 00000000000000.TH cgiwrap_putenv 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_putenv - wrap the putenv call .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgiwrap_putenv (const char *k, const char *v); .Se .SH ARGUMENTS k - the env var name .br v - the new value for env var k .SH DESCRIPTION cgiwrap_putenv wraps the putenv call. This is mostly used by the cgi_debug_init function to create an artificial environment. This version differs from the system version by having separate arguments for the variable name and value, which makes life easier for the caller (usually), and keeps most wrapping callbacks from having to implement a parser to separate them. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_init_emu.30000644001211700116100000000253510645505100016047 00000000000000.TH cgiwrap_init_emu 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_init_emu - initialize cgiwrap for emulated use .SH SYNOPSIS .Ss #include .Se .Ss void cgiwrap_init_emu (void *data, READ_FUNC read_cb, WRITEF_FUNC writef_cb, WRITE_FUNC write_cb, GETENV_FUNC getenv_cb, PUTENV_FUNC putenv_cb, ITERENV_FUNC iterenv_cb); .Se .SH ARGUMENTS data - user data to be passed to the specified callbacks .br read_cb - a cb to replace fread(stdin) .br writef_cb - a cb to repalce fprintf(stdout) .br write_cb - a cb to replace fwrite(stdout) .br getenv_cb - a cb to replace getenv .br putenv_cb - a cb to replace putenv .br iterenv_cb - a cb to replace the default environment iteration .br function (which just wraps walking the envp array) .SH DESCRIPTION cgiwrap_init_emu sets up the cgiwrap subsystem for use in an emulated environment where you are providing routines to use in place of the standard routines, ie when used to interface with a server or scripting language. See cgi/cgiwrap.h for the exact definitions of the callback functions. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_writef.30000644001211700116100000000133210645505100015530 00000000000000.TH cgiwrap_writef 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_writef - a wrapper for printf .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgiwrap_writef (const char *fmt, ...) ATTRIBUTE_PRINTF(1,2); .Se .SH ARGUMENTS fmt - standard printf fmt string and args .SH DESCRIPTION cgiwrap_writef is the formatted output command that replaces printf or fprintf(stdout) in a standard CGI .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_init_std.30000644001211700116100000000147010645505100016050 00000000000000.TH cgiwrap_init_std 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_init_std - Initialize cgiwrap with default functions .SH SYNOPSIS .Ss #include .Se .Ss void cgiwrap_init_std (int argc, char **argv, char **envp); .Se .SH ARGUMENTS the arguments to main, namely argc/argv/envp .SH DESCRIPTION cgiwrap_init_std will initialize the cgiwrap subsystem to use the default CGI functions, ie getenv/putenv/stdio. In reality, all this is doing is setting up the data for the cgiwrap_iterenv() function. .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_writevf.30000644001211700116100000000144710645505100015725 00000000000000.TH cgiwrap_writevf 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_writevf - a wrapper for vprintf .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgiwrap_writevf (const char *fmt, va_list ap); .Se .SH ARGUMENTS fmt - standard printf fmt string .br ap - stdarg argument pointer .SH DESCRIPTION cgiwrap_writevf is the formatted output command that replaces vprintf or fvprintf(stdout) in a standard CGI It is also used by cgiwrap_writef (the actual wrapped function is a v type function) .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_read.30000644001211700116100000000147210645505100015150 00000000000000.TH cgiwrap_read 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_read - cgiwrap input function .SH SYNOPSIS .Ss #include .Se .Ss void cgiwrap_read (char *buf, int buf_len, int *read_len); .Se .SH ARGUMENTS buf - a pre-allocated buffer to read the data into .br buf_len - the size of the pre-allocated buffer .SH DESCRIPTION cgiwrap_read is used to read incoming data from the client, usually from a POST or PUT HTTP request. It wraps the part of fread(stdin). .SH "RETURN VALUE" read_len - the number of bytes read into buf .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_write.30000644001211700116100000000133010645505100015360 00000000000000.TH cgiwrap_write 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_write - wrapper for the fwrite(stdout) .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgiwrap_write (const char *buf, int buf_len); .Se .SH ARGUMENTS buf - a character buffer .br buf_len - the length of the buffer in buf .SH DESCRIPTION cgiwrap_write is the block data output function for cgiwrap that replaces fwrite(stdout) in regular CGIs .SH "RETURN VALUE" None .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv clearsilver-0.10.5/man/man3/cgiwrap_getenv.30000644001211700116100000000202010645505100015513 00000000000000.TH cgiwrap_getenv 3 "12 July 2007" "ClearSilver" "cgi/cgiwrap.h" .de Ss .sp .ft CW .nf .. .de Se .fi .ft P .sp .. .SH NAME cgiwrap_getenv - the wrapper for getenv .SH SYNOPSIS .Ss #include .Se .Ss NEOERR *cgiwrap_getenv (const char *k, char **v); .Se .SH ARGUMENTS k - the environment variable to lookup .SH DESCRIPTION cgiwrap_getenv wraps the getenv function for access to environment variables, which are used to pass data to CGI scripts. This version differs from the system getenv in that it makes a copy of the value it returns, which gets around problems when wrapping this routine in garbage collected/reference counted languages by moving the ownership of the data to the calling function. .SH "RETURN VALUE" v - a newly allocated copy of the value of that variable, or .br NULL if not found. .SH "SEE ALSO" .BR cgiwrap_iterenv "(3), "cgiwrap_putenv "(3), "cgiwrap_init_emu "(3), "cgiwrap_writef "(3), "cgiwrap_init_std "(3), "cgiwrap_writevf "(3), "cgiwrap_read "(3), "cgiwrap_write "(3), "cgiwrap_getenv