avenger-0.8.5/0000755000175000017500000000000013357046620010162 500000000000000avenger-0.8.5/Makefile.in0000644000175000017500000007463413357046343012167 00000000000000# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.in am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(top_srcdir)/configure \ $(am__configure_deps) $(am__DIST_COMMON) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(sampledir)" SCRIPTS = $(libexec_SCRIPTS) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac DATA = $(sample_DATA) RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ cscope distdir dist dist-all distcheck am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ $(LISP)config.h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags CSCOPE = cscope DIST_SUBDIRS = $(SUBDIRS) am__DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/config.h.in AUTHORS \ COPYING ChangeLog INSTALL NEWS README compile config.guess \ config.sub depcomp install-sh ltmain.sh missing DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best DIST_TARGETS = dist-gzip distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEBUG = @CXXDEBUG@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CXXNOERR = @CXXNOERR@ CXXWFLAGS = @CXXWFLAGS@ CYGPATH_W = @CYGPATH_W@ DB_DIR = @DB_DIR@ DB_LIB = @DB_LIB@ DEBUG = @DEBUG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECFLAGS = @ECFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ ECXXFLAGS = @ECXXFLAGS@ EGREP = @EGREP@ ETAGS_ARGS = @ETAGS_ARGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDADD = @LDADD@ LDEPS = @LDEPS@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBPCAP = @LIBPCAP@ LIBS = @LIBS@ LIBSASL = @LIBSASL@ LIBSSL = @LIBSSL@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBM_INC = @NDBM_INC@ NDBM_LIBS = @NDBM_LIBS@ NM = @NM@ NMEDIT = @NMEDIT@ NW = @NW@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_LOGGER = @PATH_LOGGER@ PATH_MAIL_LOCAL = @PATH_MAIL_LOCAL@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PERL_POD_MAN = @PERL_POD_MAN@ POD2MAN = @POD2MAN@ RANLIB = @RANLIB@ SED = @SED@ SETUSERCONTEXTLIB = @SETUSERCONTEXTLIB@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ WFLAGS = @WFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ etcdir = @etcdir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ piddir = @piddir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sampledir = @sampledir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ LYNX = lynx SUBDIRS = libasync asmtpd util local doc etc libexec_SCRIPTS = avenger sample_DATA = INSTALL INSTALL.html CLEANFILES = core *.core *~ DISTCLEANFILES = autom4te*.cache config.status config.log avenger EXTRA_DIST = .gitignore avenger.in INSTALL.html LICENSE MAINTAINERCLEANFILES = aclocal.m4 install-sh mkinstalldirs \ missing configure config.guess config.sub config.h.in \ ltconfig ltmain.sh COPYING INSTALL Makefile.in stamp-h.in all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --gnu'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --gnu \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @test -f $@ || rm -f stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 install-libexecSCRIPTS: $(libexec_SCRIPTS) @$(NORMAL_INSTALL) @list='$(libexec_SCRIPTS)'; test -n "$(libexecdir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(libexecdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libexecdir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n' \ -e 'h;s|.*|.|' \ -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) { files[d] = files[d] " " $$1; \ if (++n[d] == $(am__install_max)) { \ print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ else { print "f", d "/" $$4, $$1 } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(libexecdir)$$dir'"; \ $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(libexecdir)$$dir" || exit $$?; \ } \ ; done uninstall-libexecSCRIPTS: @$(NORMAL_UNINSTALL) @list='$(libexec_SCRIPTS)'; test -n "$(libexecdir)" || exit 0; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 's,.*/,,;$(transform)'`; \ dir='$(DESTDIR)$(libexecdir)'; $(am__uninstall_files_from_dir) mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt install-sampleDATA: $(sample_DATA) @$(NORMAL_INSTALL) @list='$(sample_DATA)'; test -n "$(sampledir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(sampledir)'"; \ $(MKDIR_P) "$(DESTDIR)$(sampledir)" || exit 1; \ fi; \ for p in $$list; do \ if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; \ done | $(am__base_list) | \ while read files; do \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(sampledir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(sampledir)" || exit $$?; \ done uninstall-sampleDATA: @$(NORMAL_UNINSTALL) @list='$(sample_DATA)'; test -n "$(sampledir)" || list=; \ files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ dir='$(DESTDIR)$(sampledir)'; $(am__uninstall_files_from_dir) # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscope: cscope.files test ! -s cscope.files \ || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) clean-cscope: -rm -f cscope.files cscope.files: clean-cscope cscopelist cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).tar.gz $(am__post_remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__post_remove_distdir) dist-tarZ: distdir @echo WARNING: "Support for distribution archives compressed with" \ "legacy program 'compress' is deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__post_remove_distdir) dist-shar: distdir @echo WARNING: "Support for shar distribution archives is" \ "deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 shar $(distdir) | eval GZIP= gzip $(GZIP_ENV) -c >$(distdir).shar.gz $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__post_remove_distdir) dist dist-all: $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' $(am__post_remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir) chmod u+w $(distdir) mkdir $(distdir)/_build $(distdir)/_build/sub $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build/sub \ && ../../configure \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ --srcdir=../.. --prefix="$$dc_install_base" \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__post_remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile $(SCRIPTS) $(DATA) config.h installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(libexecdir)" "$(DESTDIR)$(sampledir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-sampleDATA install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-libexecSCRIPTS install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-libexecSCRIPTS uninstall-sampleDATA @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: $(am__recursive_targets) all install-am install-strip \ uninstall-am .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--refresh check check-am clean clean-cscope clean-generic \ clean-libtool cscope cscopelist-am ctags ctags-am dist \ dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \ dist-xz dist-zip distcheck distclean distclean-generic \ distclean-hdr distclean-libtool distclean-tags distcleancheck \ distdir distuninstallcheck dvi dvi-am html html-am info \ info-am install install-am install-data install-data-am \ install-dvi install-dvi-am install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-libexecSCRIPTS install-man install-pdf install-pdf-am \ install-ps install-ps-am install-sampleDATA install-strip \ installcheck installcheck-am installdirs installdirs-am \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am uninstall-hook \ uninstall-libexecSCRIPTS uninstall-sampleDATA .PRECIOUS: Makefile $(PROGRAMS): $(LDEPS) avenger: $(srcdir)/avenger.in $(top_builddir)/config.status $(BUILT_SOURCES) cd $(top_builddir) \ && CONFIG_FILES=$@ CONFIG_HEADERS= $(SHELL) ./config.status chmod +x $@ .PHONY: fmt-install fmt-install: $(LYNX) -dump $(srcdir)/INSTALL.html \ | perl -pe 'exit if /^References$$/;' \ -e 'print "\n" if (/^\s+(\d+\.|\*\s|\+\s)/' \ -e ' && !$$pre);' \ -e 'if (/^\S/ && !$$pre) { $$pre = 1; print "\n"; }' \ -e 'elsif (/^\s/ && $$pre) { $$pre = 0; print "\n"; }' \ -e 's/\[\d+\]//g; s/^(\S)/\t\t$$1/;' > $(srcdir)/INSTALL @echo Warning: you probably have to tidy up INSTALL by hand now uninstall-hook: -rmdir $(DESTDIR)/$(sampledir) # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: avenger-0.8.5/INSTALL0000644000175000017500000001313112260421006011115 00000000000000 Mail Avenger Installation Instructions The following is a brief list of things to do to install and configure Mail Avenger. Installation: Follow these steps to compile and install Mail Avenger from source. If your operating system comes with a port or package of mail avenger, you can skip ahead to Configuration. 0. Install BerkeleyDB database version 4.1 or later, if you do not already have it. Most operating systems come with an optional port/package for BerkeleyDB, making it easy to install. (Check for a package name like "db" or"db4".) Alternatively, you can download and install BerkeleyDB from http://www.sleepycat.com/. 1. Compile the software using the standard GNU autoconf script, which requires running the following commands: gzip -dc avenger-x.x.tar.gz | tar xvf - cd avenger-x.x ./configure make Note that if you want Mail Avenger to support SASL authentication, you should first install the Cyrus SASL2 library from ftp://ftp.andrew.cmu.edu/pub/cyrus-mail/, then, when following the above instructions, configure Mail Avenger using the command: ./configure --enable-sasl 2. Install the software by running the following command as root: make install Configuration: Once Mail Avenger is installed, you must configure asmtpd, the avenger SMTP daemon. 3. Create a user called avenger on your system. This is the user ID under which system-wide avenger scripts will run. (If you wish to use a name other than "avenger", you can put the directive "AvengerUser " in the asmtpd.conf configuration file when you create that.) 4. If you run sendmail, make sure the avenger user you just created has permission to read the sendmail alias database (by default /etc/mail/aliases.db). On some systems, sendmail will stubbornly keep changing the alias database so that it is only readable by group wheel, in which case you must add the avenger user to the wheel group. 5. Create the directory /etc/avenger and populate it with sample configuration files with the following commands: mkdir /etc/avenger cp /usr/local/share/avenger/asmtpd.conf /etc/avenger/ cp /usr/local/share/avenger/unknown /etc/avenger/ 6. Edit the file /etc/avenger/asmtpd.conf. By default, it is configured for sendmail. You will almost certainly need to edit it if you are using another MTA, and even with sendmail you will probably want to look over all the configuration options anyway. See the asmtpd.conf(5) man page for more information about the format of this file. 7. Edit the file /etc/avenger/unknown to handle unknown users properly. This script governs what happens to mail for users who are not in the password file, who have uid 0, or who don't have valid shells. + If you are running sendmail and your alias file is /etc/mail/aliases.db, the sample file is okay as long as the avenger user can read the aliases.db file. + If you are running qmail, you must uncomment the QMAIL_OPT line. However, this only works if you are not using the qmail users/assign file. + If you are running any other MTA, or are using qmail with the users/assign file, you will have to write your own, custom /etc/avenger/unknown script. You can alternatively just delete /etc/avenger/unknown entirely. You won't lose mail, but your system will then send back bounce messages for unknown users, which is less efficient than rejecting mail during the SMTP transaction. (Of course, asmtpd will still use SPF to reject forged mail outright.) 8. Create a file /etc/avenger/domains. List each domain for which you would like to receive mail, followed by a colon, one per line. For example: my.first.domain: my.second.domain: 9. Fire it up! Run the command asmtpd as root. You may also want to set things up to run this command automatically on system startup. Optional steps: Once you have the Avenger SMTP daemon up and running, you may wish to do any of the following. * Publish SPF records for your domains, if you haven't already. See http://www.openspf.org/ or the handy configuration wizard at http://www.openspf.org/wizard.html for more information on SPF. * Play with more scripts. Read the man page for avenger(1), create a .avenger/rcpt file in your home directory, and maybe create a site-wide default file /etc/avenger/default. * Configure the avenger local delivery agent, avenger.local. (See the avenger.local(8) man page for more information.) + If you use sendmail, include /usr/local/share/avenger/avsendmail.m4 towards the end of the ".mc" file you use to generate sendmail.cf with the following line: include(`/usr/local/share/avenger/avsendmail.m4') + If you use postfix, add the following lines to /etc/postfix/mail.cf, but be sure to substitute the correct path for mail.local: prepend_delivered_header = forward, file mailbox_command = /usr/local/libexec/avenger.local --fallback /usr/libexec/mail.local -D "$RECIPIENT" -d "$LOCAL" + If you use qmail, you don't really need to install avenger.local, because qmail already has a similar mechanism for delivering extension addresses. avenger-0.8.5/libasync/0000755000175000017500000000000013357046615011772 500000000000000avenger-0.8.5/libasync/straux.C0000644000175000017500000001147511221237220013332 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "amisc.h" /* This is the memory equivalent of strpbrk(). It finds the first * occurance of any character from s2 in s1, but takes a length * argument for s1 rather than stopping at a null byte. */ char * mempbrk (char *s1, const char *s2, int len) { const char *const eom = s1 + len; register const char *cp; register int i1, i2; while (s1 < eom) { i1 = *s1++; cp = s2; while ((i2 = *cp++)) if (i1 == i2) return (s1 - 1); } return (NULL); } /* This is a strsep function that returns a null field for adjacent * separators. This is the same as the 4.4BSD strsep, but different * from the one in the GNU libc. */ char * xstrsep(char **str, const char *delim) { char *s, *e; if (!**str) return (NULL); s = *str; e = s + strcspn (s, delim); if (*e != '\0') *e++ = '\0'; *str = e; return (s); } /* Get the next non-null token (like GNU strsep). Strsep() will * return a null token for two adjacent separators, so we may have to * loop. */ char * strnnsep (char **stringp, const char *delim) { char *tok; do { tok = xstrsep (stringp, delim); } while (tok && *tok == '\0'); return (tok); } #ifndef HAVE_STRCASECMP /* * This array is designed for mapping upper and lower case letter * together for a case independent comparison. The mappings are * based upon ascii character sequences. */ static const u_char charmap[] = { '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247', '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257', '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267', '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307', '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317', '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327', '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377', }; int strcasecmp (const char *s1, const char *s2) { const u_char *cm = charmap, *us1 = (const u_char *) s1, *us2 = (const u_char *) s2; while (cm[*us1] == cm[*us2++]) if (*us1++ == '\0') return (0); return (cm[*us1] - cm[*--us2]); } int strncasecmp (const char *s1, const char *s2, int n) { if (n != 0) { const u_char *cm = charmap, *us1 = (const u_char *) s1, *us2 = (const u_char *) s2; do { if (cm[*us1] != cm[*us2++]) return (cm[*us1] - cm[*--us2]); if (*us1++ == '\0') break; } while (--n != 0); } return (0); } #endif /* !HAVE_STRCASECMP */ avenger-0.8.5/libasync/arandom.c0000644000175000017500000000710111221237220013454 00000000000000/* $Id$ */ /* * * Copyright (C) 2003 David Mazieres (dm@uun.org) * * 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 * */ #include "sysconf.h" /* XXX - need initializer because of broken Apple Darwin linker */ u_int32_t (*arandom_fn) () = 0; #ifndef HAVE_ARC4RANDOM /* This is a simple random number generator, based on the ARC4 stream * cipher. THIS IS NOT CRYPTOGRAPHICALLY SECURE! It is simply for * getting a somewhat random-looking series of bytes. In order to get * cryptographically secure random numbers, you have to set the * arandom_fn function pointer to a real cryptographic pseudo-random * generator */ struct arc4rnd { u_char i; u_char j; u_char s[256]; }; typedef struct arc4rnd arc4rnd; static inline u_int32_t arc4rnd_getbyte (arc4rnd *a) { u_char si, sj; a->i = (a->i + 1) & 0xff; si = a->s[a->i]; a->j = (a->j + si) & 0xff; sj = a->s[a->j]; a->s[a->i] = sj; a->s[a->j] = si; return a->s[(si + sj) & 0xff]; } static void arc4rnd_reset (arc4rnd *a) { int n; a->i = 0xff; a->j = 0; for (n = 0; n < 0x100; n++) a->s[n] = n; } static void _arc4rnd_setkey (arc4rnd *a, const u_char *key, size_t keylen) { u_int n, keypos; u_char si; for (n = 0, keypos = 0; n < 256; n++, keypos++) { if (keypos >= keylen) keypos = 0; a->i = (a->i + 1) & 0xff; si = a->s[a->i]; a->j = (a->j + si + key[keypos]) & 0xff; a->s[a->i] = a->s[a->j]; a->s[a->j] = si; } } static void arc4rnd_setkey (arc4rnd *a, const void *_key, size_t len) { const u_char *key = (const u_char *) _key; arc4rnd_reset (a); while (len > 128) { len -= 128; key += 128; _arc4rnd_setkey (a, key, 128); } if (len > 0) _arc4rnd_setkey (a, key, len); a->j = a->i; } static arc4rnd bad_random_state; struct bad_random_junk { struct timespec now; pid_t pid; }; static void bad_random_init () { int i; struct bad_random_junk brj; #ifdef SFS_DEV_RANDOM int fd = open (SFS_DEV_RANDOM, O_RDONLY); if (fd >= 0) { char buf[256]; int n; if ((n = fcntl (fd, F_GETFL)) != -1 && fcntl (fd, F_SETFL, n | O_NONBLOCK) != -1 && (n = read (fd, buf, sizeof (buf))) >= 12) { close (fd); arc4rnd_setkey (&bad_random_state, buf, n); return; } close (fd); } #endif /* SFS_DEV_RANDOM */ clock_gettime (CLOCK_REALTIME, &brj.now); brj.pid = getpid (); arc4rnd_setkey (&bad_random_state, &brj, sizeof (brj)); for (i = 0; i < 256; i++) arc4rnd_getbyte (&bad_random_state); } static u_int32_t bad_random () { return arc4rnd_getbyte (&bad_random_state) | arc4rnd_getbyte (&bad_random_state) << 8 | arc4rnd_getbyte (&bad_random_state) << 16 | arc4rnd_getbyte (&bad_random_state) << 24; } #endif /* !HAVE_ARC4RANDOM */ u_int32_t arandom () { if (!arandom_fn) { #ifdef HAVE_ARC4RANDOM arandom_fn = arc4random; #else /* !HAVE_ARC4RANDOM */ bad_random_init (); arandom_fn = bad_random; #endif /* !HAVE_ARC4RANDOM */ } return (*arandom_fn) (); } avenger-0.8.5/libasync/dftables.c0000644000175000017500000001207611221235216013631 00000000000000/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by: Philip Hazel Copyright (c) 1997-2003 University of Cambridge ----------------------------------------------------------------------------- Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software 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. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), then the terms of that licence shall supersede any condition above with which it is incompatible. ----------------------------------------------------------------------------- See the file Tech.Notes for some information on the internals. */ /* This is a support program to generate the file chartables.c, containing character tables of various kinds. They are built according to the default C locale and used as the default tables by PCRE. Now that pcre_maketables is a function visible to the outside world, we make use of its code from here in order to be consistent. */ #include #include #include #include "internal.h" #define DFTABLES /* maketables.c notices this */ #include "maketables.c" int main(int argc, char **argv) { int i; FILE *f; const unsigned char *tables = pcre_maketables(); if (argc != 2) { fprintf(stderr, "dftables: one filename argument is required\n"); return 1; } f = fopen(argv[1], "w"); if (f == NULL) { fprintf(stderr, "dftables: failed to open %s for writing\n", argv[1]); return 1; } /* There are two fprintf() calls here, because gcc in pedantic mode complains about the very long string otherwise. */ fprintf(f, "/*************************************************\n" "* Perl-Compatible Regular Expressions *\n" "*************************************************/\n\n" "/* This file is automatically written by the dftables auxiliary \n" "program. If you edit it by hand, you might like to edit the Makefile to \n" "prevent its ever being regenerated.\n\n"); fprintf(f, "This file is #included in the compilation of pcre.c to build the default\n" "character tables which are used when no tables are passed to the compile\n" "function. */\n\n" "static unsigned char pcre_default_tables[] = {\n\n" "/* This table is a lower casing table. */\n\n"); fprintf(f, " "); for (i = 0; i < 256; i++) { if ((i & 7) == 0 && i != 0) fprintf(f, "\n "); fprintf(f, "%3d", *tables++); if (i != 255) fprintf(f, ","); } fprintf(f, ",\n\n"); fprintf(f, "/* This table is a case flipping table. */\n\n"); fprintf(f, " "); for (i = 0; i < 256; i++) { if ((i & 7) == 0 && i != 0) fprintf(f, "\n "); fprintf(f, "%3d", *tables++); if (i != 255) fprintf(f, ","); } fprintf(f, ",\n\n"); fprintf(f, "/* This table contains bit maps for various character classes.\n" "Each map is 32 bytes long and the bits run from the least\n" "significant end of each byte. The classes that have their own\n" "maps are: space, xdigit, digit, upper, lower, word, graph\n" "print, punct, and cntrl. Other classes are built from combinations. */\n\n"); fprintf(f, " "); for (i = 0; i < cbit_length; i++) { if ((i & 7) == 0 && i != 0) { if ((i & 31) == 0) fprintf(f, "\n"); fprintf(f, "\n "); } fprintf(f, "0x%02x", *tables++); if (i != cbit_length - 1) fprintf(f, ","); } fprintf(f, ",\n\n"); fprintf(f, "/* This table identifies various classes of character by individual bits:\n" " 0x%02x white space character\n" " 0x%02x letter\n" " 0x%02x decimal digit\n" " 0x%02x hexadecimal digit\n" " 0x%02x alphanumeric or '_'\n" " 0x%02x regular expression metacharacter or binary zero\n*/\n\n", ctype_space, ctype_letter, ctype_digit, ctype_xdigit, ctype_word, ctype_meta); fprintf(f, " "); for (i = 0; i < 256; i++) { if ((i & 7) == 0 && i != 0) { fprintf(f, " /* "); if (isprint(i-8)) fprintf(f, " %c -", i-8); else fprintf(f, "%3d-", i-8); if (isprint(i-1)) fprintf(f, " %c ", i-1); else fprintf(f, "%3d", i-1); fprintf(f, " */\n "); } fprintf(f, "0x%02x", *tables++); if (i != 255) fprintf(f, ","); } fprintf(f, "};/* "); if (isprint(i-8)) fprintf(f, " %c -", i-8); else fprintf(f, "%3d-", i-8); if (isprint(i-1)) fprintf(f, " %c ", i-1); else fprintf(f, "%3d", i-1); fprintf(f, " */\n\n/* End of chartables.c */\n"); fclose(f); return 0; } /* End of dftables.c */ avenger-0.8.5/libasync/refcnt.C0000644000175000017500000000361411332761414013273 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "refcnt.h" /* * XXX - workaround for egregious egcs bug. * * On OpenBSD, egcs does not support inline functions with static * variables properly. For example, what we want is: * class __globaldestruction_t { * bool &started () { static bool val; return val; } * public: * ~__globaldestruction_t () { started () = true; } * operator bool () { return started () } * }; * But that doesn't work, so we need a whole file just for one bit! */ bool __globaldestruction_t::started; /* * XXX - for lack of a better place to put this: */ #include "callback.h" static void ignore_void () { } static void ignore_int (int) { } callback::ref cbv_null (gwrap (ignore_void)); callback::ref cbi_null (gwrap (ignore_int)); #include "err.h" #include void refcnt_warn (const char *op, const std::type_info &type, void *addr, int cnt) { char buf[1024]; sprintf (buf, "%.128s%s%.64s: %.512s (%p) -> %d\n", progname ? progname.cstr () : "", progname ? ": " : "", op, type.name (), addr, cnt); assert (memchr (buf, 0, sizeof (buf))); use (write (errfd, buf, strlen (buf))); } avenger-0.8.5/libasync/Makefile.in0000644000175000017500000006344313357046344013770 00000000000000# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ # Note: The files # internal.h pcre.h dftables.c maketables.c pcre.c study.c # are from pcre-4.5, the perl compatible regular expression library. # Pcre was written by Philip Hazel, and is distributed from # http://www.pcre.org/ # ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ noinst_PROGRAMS = dftables$(EXEEXT) subdir = libasync ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.in am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(noinst_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) ARFLAGS = cru AM_V_AR = $(am__v_AR_@AM_V@) am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = libasync_a_AR = $(AR) $(ARFLAGS) libasync_a_LIBADD = am_libasync_a_OBJECTS = arandom.$(OBJEXT) clock_gettime.$(OBJEXT) \ getopt_long.$(OBJEXT) maketables.$(OBJEXT) pcre.$(OBJEXT) \ rwfd.$(OBJEXT) stktrace.$(OBJEXT) study.$(OBJEXT) \ suidprotect.$(OBJEXT) aerr.$(OBJEXT) aios.$(OBJEXT) \ arena.$(OBJEXT) armor.$(OBJEXT) cbuf.$(OBJEXT) \ convertint.$(OBJEXT) core.$(OBJEXT) daemonize.$(OBJEXT) \ dns.$(OBJEXT) dnsparse.$(OBJEXT) err.$(OBJEXT) ident.$(OBJEXT) \ ifchg.$(OBJEXT) ihash.$(OBJEXT) itree.$(OBJEXT) \ malloc.$(OBJEXT) msb.$(OBJEXT) myaddrs.$(OBJEXT) \ myname.$(OBJEXT) parseopt.$(OBJEXT) pipe2str.$(OBJEXT) \ refcnt.$(OBJEXT) resolvconf.$(OBJEXT) rxx.$(OBJEXT) \ socket.$(OBJEXT) spawn.$(OBJEXT) str.$(OBJEXT) \ str2file.$(OBJEXT) straux.$(OBJEXT) suio++.$(OBJEXT) \ suio_vuprintf.$(OBJEXT) tcpconnect.$(OBJEXT) libasync_a_OBJECTS = $(am_libasync_a_OBJECTS) PROGRAMS = $(noinst_PROGRAMS) am_dftables_OBJECTS = dftables.$(OBJEXT) dftables_OBJECTS = $(am_dftables_OBJECTS) dftables_DEPENDENCIES = AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libasync_a_SOURCES) $(dftables_SOURCES) DIST_SOURCES = $(libasync_a_SOURCES) $(dftables_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEBUG = @CXXDEBUG@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CXXNOERR = @CXXNOERR@ CXXWFLAGS = @CXXWFLAGS@ CYGPATH_W = @CYGPATH_W@ DB_DIR = @DB_DIR@ DB_LIB = @DB_LIB@ DEBUG = @DEBUG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECFLAGS = @ECFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ ECXXFLAGS = @ECXXFLAGS@ EGREP = @EGREP@ ETAGS_ARGS = @ETAGS_ARGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDADD = @LDADD@ LDEPS = @LDEPS@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBPCAP = @LIBPCAP@ LIBS = @LIBS@ LIBSASL = @LIBSASL@ LIBSSL = @LIBSSL@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBM_INC = @NDBM_INC@ NDBM_LIBS = @NDBM_LIBS@ NM = @NM@ NMEDIT = @NMEDIT@ NW = @NW@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_LOGGER = @PATH_LOGGER@ PATH_MAIL_LOCAL = @PATH_MAIL_LOCAL@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PERL_POD_MAN = @PERL_POD_MAN@ POD2MAN = @POD2MAN@ RANLIB = @RANLIB@ SED = @SED@ SETUSERCONTEXTLIB = @SETUSERCONTEXTLIB@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ WFLAGS = @WFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ etcdir = @etcdir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ piddir = @piddir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sampledir = @sampledir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ noinst_LIBRARIES = libasync.a libasync_a_SOURCES = \ arandom.c clock_gettime.c getopt_long.c maketables.c pcre.c rwfd.c stktrace.c study.c suidprotect.c \ aerr.C aios.C arena.C armor.C cbuf.C convertint.C core.C daemonize.C dns.C dnsparse.C err.C ident.C ifchg.C ihash.C itree.C malloc.C msb.C myaddrs.C myname.C parseopt.C pipe2str.C refcnt.C resolvconf.C rxx.C socket.C spawn.C str.C str2file.C straux.C suio++.C suio_vuprintf.C tcpconnect.C noinst_HEADERS = \ aios.h amisc.h arena.h array.h async.h autoconf.h backoff.h bitvec.h callback.h cbuf.h dns.h dnsimpl.h dnsparse.h err.h fdlim.h getopt_long.h ihash.h init.h internal.h itree.h keyfunc.h list.h msb.h opnew.h parseopt.h pcre.h qhash.h refcnt.h rwfd.h rxx.h serial.h stllike.h str.h suio++.h sysconf.h union.h vatmpl.h vec.h dftables_SOURCES = dftables.c dftables_LDADD = DEPEND_ON_MAKEFILE = daemonize.o daemonize.lo spawn.o spawn.lo EXTRA_DIST = .gitignore CLEANFILES = core *.core *~ *.rpo dftables chartables.c stamp-async-repo MAINTAINERCLEANFILES = Makefile.in all: all-am .SUFFIXES: .SUFFIXES: .C .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu libasync/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu libasync/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) libasync.a: $(libasync_a_OBJECTS) $(libasync_a_DEPENDENCIES) $(EXTRA_libasync_a_DEPENDENCIES) $(AM_V_at)-rm -f libasync.a $(AM_V_AR)$(libasync_a_AR) libasync.a $(libasync_a_OBJECTS) $(libasync_a_LIBADD) $(AM_V_at)$(RANLIB) libasync.a clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list dftables$(EXEEXT): $(dftables_OBJECTS) $(dftables_DEPENDENCIES) $(EXTRA_dftables_DEPENDENCIES) @rm -f dftables$(EXEEXT) $(AM_V_CCLD)$(LINK) $(dftables_OBJECTS) $(dftables_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/aerr.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/aios.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/arandom.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/arena.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/armor.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cbuf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/clock_gettime.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/convertint.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/core.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/daemonize.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dftables.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dns.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dnsparse.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/err.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getopt_long.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ident.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ifchg.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ihash.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/itree.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/maketables.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/malloc.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/msb.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/myaddrs.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/myname.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/parseopt.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pcre.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pipe2str.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/refcnt.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/resolvconf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rwfd.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/rxx.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/socket.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/spawn.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/stktrace.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/str2file.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/straux.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/study.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/suidprotect.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/suio++.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/suio_vuprintf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/tcpconnect.Po@am__quote@ .C.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .C.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .C.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LIBRARIES) $(PROGRAMS) $(HEADERS) installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLIBRARIES \ clean-noinstPROGRAMS mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ clean-libtool clean-noinstLIBRARIES clean-noinstPROGRAMS \ cscopelist-am ctags ctags-am distclean distclean-compile \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags tags-am uninstall uninstall-am .PRECIOUS: Makefile pcre.o pcre.lo: chartables.c chartables.c: dftables ./dftables $@ $(DEPEND_ON_MAKEFILE): Makefile stktrace.o: $(srcdir)/stktrace.c $(srcdir)/sysconf.h $(COMPILE) $(NW) -c $(srcdir)/stktrace.c # This assumes sfs1 is a symlink to the SFS sources .PHONY: getsrc getsrc: @set -ex; \ for file in $(libasync_a_SOURCES) $(noinst_HEADERS); do \ case $$file in \ autoconf.h|chartables.c|getopt_long.*) \ ;; \ *) \ cp $(srcdir)/sfs1/async/$$file $(srcdir)/ \ ;; \ esac; \ done # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: avenger-0.8.5/libasync/internal.h0000644000175000017500000007133511221235746013701 00000000000000/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* This is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. See the file Tech.Notes for some information on the internals. Written by: Philip Hazel Copyright (c) 1997-2003 University of Cambridge ----------------------------------------------------------------------------- Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software 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. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), then the terms of that licence shall supersede any condition above with which it is incompatible. ----------------------------------------------------------------------------- */ /* This header contains definitions that are shared between the different modules, but which are not relevant to the outside. */ /* Get the definitions provided by running "configure" */ #include "sysconf.h" #ifndef EBCDIC #define EBCDIC 0 #endif #define EXPORT #ifndef NEWLINE #define NEWLINE '\n' #endif #ifndef LINK_SIZE #define LINK_SIZE 2 #endif #ifndef MATCH_LIMIT #define MATCH_LIMIT 10000000 #endif #ifndef POSIX_MALLOC_THRESHOLD #define POSIX_MALLOC_THRESHOLD 10 #endif #ifndef HAVE_MEMMOVE #define HAVE_MEMMOVE 1 #endif /* Standard C headers plus the external interface definition. The only time setjmp and stdarg are used is when NO_RECURSE is set. */ #include #include #include #include #include #include #include #include #ifndef PCRE_SPY #define PCRE_DEFINITION /* Win32 __declspec(export) trigger for .dll */ #endif #include "pcre.h" /* When compiling for use with the Virtual Pascal compiler, these functions need to have their names changed. PCRE must be compiled with the -DVPCOMPAT option on the command line. */ #ifdef VPCOMPAT #define strncmp(s1,s2,m) _strncmp(s1,s2,m) #define memcpy(d,s,n) _memcpy(d,s,n) #define memmove(d,s,n) _memmove(d,s,n) #define memset(s,c,n) _memset(s,c,n) #else /* VPCOMPAT */ /* To cope with SunOS4 and other systems that lack memmove() but have bcopy(), define a macro for memmove() if HAVE_MEMMOVE is false, provided that HAVE_BCOPY is set. Otherwise, include an emulating function for those systems that have neither (there some non-Unix environments where this is the case). This assumes that all calls to memmove are moving strings upwards in store, which is the case in PCRE. */ #if ! HAVE_MEMMOVE #undef memmove /* some systems may have a macro */ #if HAVE_BCOPY #define memmove(a, b, c) bcopy(b, a, c) #else /* HAVE_BCOPY */ static inline void pcre_memmove(unsigned char *dest, const unsigned char *src, size_t n) { int i; dest += n; src += n; for (i = 0; i < n; ++i) *(--dest) = *(--src); } #define memmove(a, b, c) pcre_memmove(a, b, c) #endif /* not HAVE_BCOPY */ #endif /* not HAVE_MEMMOVE */ #endif /* not VPCOMPAT */ /* PCRE keeps offsets in its compiled code as 2-byte quantities by default. These are used, for example, to link from the start of a subpattern to its alternatives and its end. The use of 2 bytes per offset limits the size of the compiled regex to around 64K, which is big enough for almost everybody. However, I received a request for an even bigger limit. For this reason, and also to make the code easier to maintain, the storing and loading of offsets from the byte string is now handled by the macros that are defined here. The macros are controlled by the value of LINK_SIZE. This defaults to 2 in the config.h file, but can be overridden by using -D on the command line. This is automated on Unix systems via the "configure" command. */ #if LINK_SIZE == 2 #define PUT(a,n,d) \ (a[n] = (d) >> 8), \ (a[(n)+1] = (d) & 255) #define GET(a,n) \ (((a)[n] << 8) | (a)[(n)+1]) #define MAX_PATTERN_SIZE (1 << 16) #elif LINK_SIZE == 3 #define PUT(a,n,d) \ (a[n] = (d) >> 16), \ (a[(n)+1] = (d) >> 8), \ (a[(n)+2] = (d) & 255) #define GET(a,n) \ (((a)[n] << 16) | ((a)[(n)+1] << 8) | (a)[(n)+2]) #define MAX_PATTERN_SIZE (1 << 24) #elif LINK_SIZE == 4 #define PUT(a,n,d) \ (a[n] = (d) >> 24), \ (a[(n)+1] = (d) >> 16), \ (a[(n)+2] = (d) >> 8), \ (a[(n)+3] = (d) & 255) #define GET(a,n) \ (((a)[n] << 24) | ((a)[(n)+1] << 16) | ((a)[(n)+2] << 8) | (a)[(n)+3]) #define MAX_PATTERN_SIZE (1 << 30) /* Keep it positive */ #else #error LINK_SIZE must be either 2, 3, or 4 #endif /* Convenience macro defined in terms of the others */ #define PUTINC(a,n,d) PUT(a,n,d), a += LINK_SIZE /* PCRE uses some other 2-byte quantities that do not change when the size of offsets changes. There are used for repeat counts and for other things such as capturing parenthesis numbers in back references. */ #define PUT2(a,n,d) \ a[n] = (d) >> 8; \ a[(n)+1] = (d) & 255 #define GET2(a,n) \ (((a)[n] << 8) | (a)[(n)+1]) #define PUT2INC(a,n,d) PUT2(a,n,d), a += 2 /* In case there is no definition of offsetof() provided - though any proper Standard C system should have one. */ #ifndef offsetof #define offsetof(p_type,field) ((size_t)&(((p_type *)0)->field)) #endif /* These are the public options that can change during matching. */ #define PCRE_IMS (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL) /* Private options flags start at the most significant end of the four bytes, but skip the top bit so we can use ints for convenience without getting tangled with negative values. The public options defined in pcre.h start at the least significant end. Make sure they don't overlap, though now that we have expanded to four bytes there is plenty of space. */ #define PCRE_FIRSTSET 0x40000000 /* first_byte is set */ #define PCRE_REQCHSET 0x20000000 /* req_byte is set */ #define PCRE_STARTLINE 0x10000000 /* start after \n for multiline */ #define PCRE_ICHANGED 0x08000000 /* i option changes within regex */ /* Options for the "extra" block produced by pcre_study(). */ #define PCRE_STUDY_MAPPED 0x01 /* a map of starting chars exists */ /* Masks for identifying the public options which are permitted at compile time, run time or study time, respectively. */ #define PUBLIC_OPTIONS \ (PCRE_CASELESS|PCRE_EXTENDED|PCRE_ANCHORED|PCRE_MULTILINE| \ PCRE_DOTALL|PCRE_DOLLAR_ENDONLY|PCRE_EXTRA|PCRE_UNGREEDY|PCRE_UTF8| \ PCRE_NO_AUTO_CAPTURE|PCRE_NO_UTF8_CHECK) #define PUBLIC_EXEC_OPTIONS \ (PCRE_ANCHORED|PCRE_NOTBOL|PCRE_NOTEOL|PCRE_NOTEMPTY|PCRE_NO_UTF8_CHECK) #define PUBLIC_STUDY_OPTIONS 0 /* None defined */ /* Magic number to provide a small check against being handed junk. */ #define MAGIC_NUMBER 0x50435245UL /* 'PCRE' */ /* Negative values for the firstchar and reqchar variables */ #define REQ_UNSET (-2) #define REQ_NONE (-1) /* Flags added to firstbyte or reqbyte; a "non-literal" item is either a variable-length repeat, or a anything other than literal characters. */ #define REQ_CASELESS 0x0100 /* indicates caselessness */ #define REQ_VARY 0x0200 /* reqbyte followed non-literal item */ /* Miscellaneous definitions */ typedef int BOOL; #define FALSE 0 #define TRUE 1 /* Escape items that are just an encoding of a particular data value. Note that ESC_n is defined as yet another macro, which is set in config.h to either \n (the default) or \r (which some people want). */ #ifndef ESC_e #define ESC_e 27 #endif #ifndef ESC_f #define ESC_f '\f' #endif #ifndef ESC_n #define ESC_n NEWLINE #endif #ifndef ESC_r #define ESC_r '\r' #endif /* We can't officially use ESC_t because it is a POSIX reserved identifier (presumably because of all the others like size_t). */ #ifndef ESC_tee #define ESC_tee '\t' #endif /* These are escaped items that aren't just an encoding of a particular data value such as \n. They must have non-zero values, as check_escape() returns their negation. Also, they must appear in the same order as in the opcode definitions below, up to ESC_z. There's a dummy for OP_ANY because it corresponds to "." rather than an escape sequence. The final one must be ESC_REF as subsequent values are used for \1, \2, \3, etc. There is are two tests in the code for an escape greater than ESC_b and less than ESC_Z to detect the types that may be repeated. These are the types that consume a character. If any new escapes are put in between that don't consume a character, that code will have to change. */ enum { ESC_A = 1, ESC_G, ESC_B, ESC_b, ESC_D, ESC_d, ESC_S, ESC_s, ESC_W, ESC_w, ESC_dum1, ESC_C, ESC_Z, ESC_z, ESC_E, ESC_Q, ESC_REF }; /* Flag bits and data types for the extended class (OP_XCLASS) for classes that contain UTF-8 characters with values greater than 255. */ #define XCL_NOT 0x01 /* Flag: this is a negative class */ #define XCL_MAP 0x02 /* Flag: a 32-byte map is present */ #define XCL_END 0 /* Marks end of individual items */ #define XCL_SINGLE 1 /* Single item (one multibyte char) follows */ #define XCL_RANGE 2 /* A range (two multibyte chars) follows */ /* Opcode table: OP_BRA must be last, as all values >= it are used for brackets that extract substrings. Starting from 1 (i.e. after OP_END), the values up to OP_EOD must correspond in order to the list of escapes immediately above. Note that whenever this list is updated, the two macro definitions that follow must also be updated to match. */ enum { OP_END, /* 0 End of pattern */ /* Values corresponding to backslashed metacharacters */ OP_SOD, /* 1 Start of data: \A */ OP_SOM, /* 2 Start of match (subject + offset): \G */ OP_NOT_WORD_BOUNDARY, /* 3 \B */ OP_WORD_BOUNDARY, /* 4 \b */ OP_NOT_DIGIT, /* 5 \D */ OP_DIGIT, /* 6 \d */ OP_NOT_WHITESPACE, /* 7 \S */ OP_WHITESPACE, /* 8 \s */ OP_NOT_WORDCHAR, /* 9 \W */ OP_WORDCHAR, /* 10 \w */ OP_ANY, /* 11 Match any character */ OP_ANYBYTE, /* 12 Match any byte (\C); different to OP_ANY for UTF-8 */ OP_EODN, /* 13 End of data or \n at end of data: \Z. */ OP_EOD, /* 14 End of data: \z */ OP_OPT, /* 15 Set runtime options */ OP_CIRC, /* 16 Start of line - varies with multiline switch */ OP_DOLL, /* 17 End of line - varies with multiline switch */ OP_CHARS, /* 18 Match string of characters */ OP_NOT, /* 19 Match anything but the following char */ OP_STAR, /* 20 The maximizing and minimizing versions of */ OP_MINSTAR, /* 21 all these opcodes must come in pairs, with */ OP_PLUS, /* 22 the minimizing one second. */ OP_MINPLUS, /* 23 This first set applies to single characters */ OP_QUERY, /* 24 */ OP_MINQUERY, /* 25 */ OP_UPTO, /* 26 From 0 to n matches */ OP_MINUPTO, /* 27 */ OP_EXACT, /* 28 Exactly n matches */ OP_NOTSTAR, /* 29 The maximizing and minimizing versions of */ OP_NOTMINSTAR, /* 30 all these opcodes must come in pairs, with */ OP_NOTPLUS, /* 31 the minimizing one second. */ OP_NOTMINPLUS, /* 32 This set applies to "not" single characters */ OP_NOTQUERY, /* 33 */ OP_NOTMINQUERY, /* 34 */ OP_NOTUPTO, /* 35 From 0 to n matches */ OP_NOTMINUPTO, /* 36 */ OP_NOTEXACT, /* 37 Exactly n matches */ OP_TYPESTAR, /* 38 The maximizing and minimizing versions of */ OP_TYPEMINSTAR, /* 39 all these opcodes must come in pairs, with */ OP_TYPEPLUS, /* 40 the minimizing one second. These codes must */ OP_TYPEMINPLUS, /* 41 be in exactly the same order as those above. */ OP_TYPEQUERY, /* 42 This set applies to character types such as \d */ OP_TYPEMINQUERY, /* 43 */ OP_TYPEUPTO, /* 44 From 0 to n matches */ OP_TYPEMINUPTO, /* 45 */ OP_TYPEEXACT, /* 46 Exactly n matches */ OP_CRSTAR, /* 47 The maximizing and minimizing versions of */ OP_CRMINSTAR, /* 48 all these opcodes must come in pairs, with */ OP_CRPLUS, /* 49 the minimizing one second. These codes must */ OP_CRMINPLUS, /* 50 be in exactly the same order as those above. */ OP_CRQUERY, /* 51 These are for character classes and back refs */ OP_CRMINQUERY, /* 52 */ OP_CRRANGE, /* 53 These are different to the three seta above. */ OP_CRMINRANGE, /* 54 */ OP_CLASS, /* 55 Match a character class, chars < 256 only */ OP_NCLASS, /* 56 Same, but the bitmap was created from a negative class - the difference is relevant only when a UTF-8 character > 255 is encountered. */ OP_XCLASS, /* 57 Extended class for handling UTF-8 chars within the class. This does both positive and negative. */ OP_REF, /* 58 Match a back reference */ OP_RECURSE, /* 59 Match a numbered subpattern (possibly recursive) */ OP_CALLOUT, /* 60 Call out to external function if provided */ OP_ALT, /* 61 Start of alternation */ OP_KET, /* 62 End of group that doesn't have an unbounded repeat */ OP_KETRMAX, /* 63 These two must remain together and in this */ OP_KETRMIN, /* 64 order. They are for groups the repeat for ever. */ /* The assertions must come before ONCE and COND */ OP_ASSERT, /* 65 Positive lookahead */ OP_ASSERT_NOT, /* 66 Negative lookahead */ OP_ASSERTBACK, /* 67 Positive lookbehind */ OP_ASSERTBACK_NOT, /* 68 Negative lookbehind */ OP_REVERSE, /* 69 Move pointer back - used in lookbehind assertions */ /* ONCE and COND must come after the assertions, with ONCE first, as there's a test for >= ONCE for a subpattern that isn't an assertion. */ OP_ONCE, /* 70 Once matched, don't back up into the subpattern */ OP_COND, /* 71 Conditional group */ OP_CREF, /* 72 Used to hold an extraction string number (cond ref) */ OP_BRAZERO, /* 73 These two must remain together and in this */ OP_BRAMINZERO, /* 74 order. */ OP_BRANUMBER, /* 75 Used for extracting brackets whose number is greater than can fit into an opcode. */ OP_BRA /* 76 This and greater values are used for brackets that extract substrings up to a basic limit. After that, use is made of OP_BRANUMBER. */ }; /* WARNING: There is an implicit assumption in study.c that all opcodes are less than 128 in value. This makes handling UTF-8 character sequences easier. */ /* This macro defines textual names for all the opcodes. There are used only for debugging, in pcre.c when DEBUG is defined, and also in pcretest.c. The macro is referenced only in printint.c. */ #define OP_NAME_LIST \ "End", "\\A", "\\G", "\\B", "\\b", "\\D", "\\d", \ "\\S", "\\s", "\\W", "\\w", "Any", "Anybyte", "\\Z", "\\z", \ "Opt", "^", "$", "chars", "not", \ "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ "*", "*?", "+", "+?", "?", "??", "{", "{", "{", \ "*", "*?", "+", "+?", "?", "??", "{", "{", \ "class", "nclass", "xclass", "Ref", "Recurse", "Callout", \ "Alt", "Ket", "KetRmax", "KetRmin", "Assert", "Assert not", \ "AssertB", "AssertB not", "Reverse", "Once", "Cond", "Cond ref",\ "Brazero", "Braminzero", "Branumber", "Bra" /* This macro defines the length of fixed length operations in the compiled regex. The lengths are used when searching for specific things, and also in the debugging printing of a compiled regex. We use a macro so that it can be incorporated both into pcre.c and pcretest.c without being publicly exposed. As things have been extended, some of these are no longer fixed lenths, but are minima instead. For example, the length of a single-character repeat may vary in UTF-8 mode. The code that uses this table must know about such things. */ #define OP_LENGTHS \ 1, /* End */ \ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* \A, \G, \B, \B, \D, \d, \S, \s, \W, \w */ \ 1, 1, 1, 1, 2, 1, 1, /* Any, Anybyte, \Z, \z, Opt, ^, $ */ \ 2, /* Chars - the minimum length */ \ 2, /* not */ \ /* Positive single-char repeats ** These are */ \ 2, 2, 2, 2, 2, 2, /* *, *?, +, +?, ?, ?? ** minima in */ \ 4, 4, 4, /* upto, minupto, exact ** UTF-8 mode */ \ /* Negative single-char repeats - only for chars < 256 */ \ 2, 2, 2, 2, 2, 2, /* NOT *, *?, +, +?, ?, ?? */ \ 4, 4, 4, /* NOT upto, minupto, exact */ \ /* Positive type repeats */ \ 2, 2, 2, 2, 2, 2, /* Type *, *?, +, +?, ?, ?? */ \ 4, 4, 4, /* Type upto, minupto, exact */ \ /* Character class & ref repeats */ \ 1, 1, 1, 1, 1, 1, /* *, *?, +, +?, ?, ?? */ \ 5, 5, /* CRRANGE, CRMINRANGE */ \ 33, /* CLASS */ \ 33, /* NCLASS */ \ 0, /* XCLASS - variable length */ \ 3, /* REF */ \ 1+LINK_SIZE, /* RECURSE */ \ 2, /* CALLOUT */ \ 1+LINK_SIZE, /* Alt */ \ 1+LINK_SIZE, /* Ket */ \ 1+LINK_SIZE, /* KetRmax */ \ 1+LINK_SIZE, /* KetRmin */ \ 1+LINK_SIZE, /* Assert */ \ 1+LINK_SIZE, /* Assert not */ \ 1+LINK_SIZE, /* Assert behind */ \ 1+LINK_SIZE, /* Assert behind not */ \ 1+LINK_SIZE, /* Reverse */ \ 1+LINK_SIZE, /* Once */ \ 1+LINK_SIZE, /* COND */ \ 3, /* CREF */ \ 1, 1, /* BRAZERO, BRAMINZERO */ \ 3, /* BRANUMBER */ \ 1+LINK_SIZE /* BRA */ \ /* The highest extraction number before we have to start using additional bytes. (Originally PCRE didn't have support for extraction counts highter than this number.) The value is limited by the number of opcodes left after OP_BRA, i.e. 255 - OP_BRA. We actually set it a bit lower to leave room for additional opcodes. */ #define EXTRACT_BASIC_MAX 150 /* A magic value for OP_CREF to indicate the "in recursion" condition. */ #define CREF_RECURSE 0xffff /* The texts of compile-time error messages are defined as macros here so that they can be accessed by the POSIX wrapper and converted into error codes. Yes, I could have used error codes in the first place, but didn't feel like changing just to accommodate the POSIX wrapper. */ #define ERR1 "\\ at end of pattern" #define ERR2 "\\c at end of pattern" #define ERR3 "unrecognized character follows \\" #define ERR4 "numbers out of order in {} quantifier" #define ERR5 "number too big in {} quantifier" #define ERR6 "missing terminating ] for character class" #define ERR7 "invalid escape sequence in character class" #define ERR8 "range out of order in character class" #define ERR9 "nothing to repeat" #define ERR10 "operand of unlimited repeat could match the empty string" #define ERR11 "internal error: unexpected repeat" #define ERR12 "unrecognized character after (?" #define ERR13 "POSIX named classes are supported only within a class" #define ERR14 "missing )" #define ERR15 "reference to non-existent subpattern" #define ERR16 "erroffset passed as NULL" #define ERR17 "unknown option bit(s) set" #define ERR18 "missing ) after comment" #define ERR19 "parentheses nested too deeply" #define ERR20 "regular expression too large" #define ERR21 "failed to get memory" #define ERR22 "unmatched parentheses" #define ERR23 "internal error: code overflow" #define ERR24 "unrecognized character after (?<" #define ERR25 "lookbehind assertion is not fixed length" #define ERR26 "malformed number after (?(" #define ERR27 "conditional group contains more than two branches" #define ERR28 "assertion expected after (?(" #define ERR29 "(?R or (?digits must be followed by )" #define ERR30 "unknown POSIX class name" #define ERR31 "POSIX collating elements are not supported" #define ERR32 "this version of PCRE is not compiled with PCRE_UTF8 support" #define ERR33 "spare error" #define ERR34 "character value in \\x{...} sequence is too large" #define ERR35 "invalid condition (?(0)" #define ERR36 "\\C not allowed in lookbehind assertion" #define ERR37 "PCRE does not support \\L, \\l, \\N, \\P, \\p, \\U, \\u, or \\X" #define ERR38 "number after (?C is > 255" #define ERR39 "closing ) for (?C expected" #define ERR40 "recursive call could loop indefinitely" #define ERR41 "unrecognized character after (?P" #define ERR42 "syntax error after (?P" #define ERR43 "two named groups have the same name" #define ERR44 "invalid UTF-8 string" /* All character handling must be done as unsigned characters. Otherwise there are problems with top-bit-set characters and functions such as isspace(). However, we leave the interface to the outside world as char *, because that should make things easier for callers. We define a short type for unsigned char to save lots of typing. I tried "uchar", but it causes problems on Digital Unix, where it is defined in sys/types, so use "uschar" instead. */ typedef unsigned char uschar; /* The real format of the start of the pcre block; the index of names and the code vector run on as long as necessary after the end. */ typedef struct real_pcre { unsigned long int magic_number; size_t size; /* Total that was malloced */ const unsigned char *tables; /* Pointer to tables */ unsigned long int options; unsigned short int top_bracket; unsigned short int top_backref; unsigned short int first_byte; unsigned short int req_byte; unsigned short int name_entry_size; /* Size of any name items; 0 => none */ unsigned short int name_count; /* Number of name items */ } real_pcre; /* The format of the block used to store data from pcre_study(). */ typedef struct pcre_study_data { size_t size; /* Total that was malloced */ uschar options; uschar start_bits[32]; } pcre_study_data; /* Structure for passing "static" information around between the functions doing the compiling, so that they are thread-safe. */ typedef struct compile_data { const uschar *lcc; /* Points to lower casing table */ const uschar *fcc; /* Points to case-flipping table */ const uschar *cbits; /* Points to character type table */ const uschar *ctypes; /* Points to table of type maps */ const uschar *start_code; /* The start of the compiled code */ uschar *name_table; /* The name/number table */ int names_found; /* Number of entries so far */ int name_entry_size; /* Size of each entry */ int top_backref; /* Maximum back reference */ unsigned int backref_map; /* Bitmap of low back refs */ int req_varyopt; /* "After variable item" flag for reqbyte */ } compile_data; /* Structure for maintaining a chain of pointers to the currently incomplete branches, for testing for left recursion. */ typedef struct branch_chain { struct branch_chain *outer; uschar *current; } branch_chain; /* Structure for items in a linked list that represents an explicit recursive call within the pattern. */ typedef struct recursion_info { struct recursion_info *prevrec; /* Previous recursion record (or NULL) */ int group_num; /* Number of group that was called */ const uschar *after_call; /* "Return value": points after the call in the expr */ const uschar *save_start; /* Old value of md->start_match */ int *offset_save; /* Pointer to start of saved offsets */ int saved_max; /* Number of saved offsets */ } recursion_info; /* When compiling in a mode that doesn't use recursive calls to match(), a structure is used to remember local variables on the heap. It is defined in pcre.c, close to the match() function, so that it is easy to keep it in step with any changes of local variable. However, the pointer to the current frame must be saved in some "static" place over a longjmp(). We declare the structure here so that we can put a pointer in the match_data structure. NOTE: This isn't used for a "normal" compilation of pcre. */ struct heapframe; /* Structure for passing "static" information around between the functions doing the matching, so that they are thread-safe. */ typedef struct match_data { unsigned long int match_call_count; /* As it says */ unsigned long int match_limit;/* As it says */ int *offset_vector; /* Offset vector */ int offset_end; /* One past the end */ int offset_max; /* The maximum usable for return data */ const uschar *lcc; /* Points to lower casing table */ const uschar *ctypes; /* Points to table of type maps */ BOOL offset_overflow; /* Set if too many extractions */ BOOL notbol; /* NOTBOL flag */ BOOL noteol; /* NOTEOL flag */ BOOL utf8; /* UTF8 flag */ BOOL endonly; /* Dollar not before final \n */ BOOL notempty; /* Empty string match not wanted */ const uschar *start_code; /* For use when recursing */ const uschar *start_subject; /* Start of the subject string */ const uschar *end_subject; /* End of the subject string */ const uschar *start_match; /* Start of this match attempt */ const uschar *end_match_ptr; /* Subject position at end match */ int end_offset_top; /* Highwater mark at end of match */ int capture_last; /* Most recent capture number */ int start_offset; /* The start offset value */ recursion_info *recursive; /* Linked list of recursion data */ void *callout_data; /* To pass back to callouts */ struct heapframe *thisframe; /* Used only when compiling for no recursion */ } match_data; /* Bit definitions for entries in the pcre_ctypes table. */ #define ctype_space 0x01 #define ctype_letter 0x02 #define ctype_digit 0x04 #define ctype_xdigit 0x08 #define ctype_word 0x10 /* alphameric or '_' */ #define ctype_meta 0x80 /* regexp meta char or zero (end pattern) */ /* Offsets for the bitmap tables in pcre_cbits. Each table contains a set of bits for a class map. Some classes are built by combining these tables. */ #define cbit_space 0 /* [:space:] or \s */ #define cbit_xdigit 32 /* [:xdigit:] */ #define cbit_digit 64 /* [:digit:] or \d */ #define cbit_upper 96 /* [:upper:] */ #define cbit_lower 128 /* [:lower:] */ #define cbit_word 160 /* [:word:] or \w */ #define cbit_graph 192 /* [:graph:] */ #define cbit_print 224 /* [:print:] */ #define cbit_punct 256 /* [:punct:] */ #define cbit_cntrl 288 /* [:cntrl:] */ #define cbit_length 320 /* Length of the cbits table */ /* Offsets of the various tables from the base tables pointer, and total length. */ #define lcc_offset 0 #define fcc_offset 256 #define cbits_offset 512 #define ctypes_offset (cbits_offset + cbit_length) #define tables_length (ctypes_offset + 256) /* End of internal.h */ avenger-0.8.5/libasync/ident.C0000644000175000017500000000616011221237220013102 00000000000000/* $Id$ */ /* * * Copyright (C) 1999 David Mazieres (dm@uun.org) * * 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 * */ #include "rxx.h" #include "async.h" #include "dns.h" #include "aios.h" #define AUTH_PORT 113 static rxx identrx ("^([^:]*:){3}\\s*(.*?)\\s*$"); struct identstat { ptr a; int ncb; int err; str user; str host; ptr h; callback, int>::ptr cb; void cbdone (); void identcb (str u, int e) { if (u && identrx.search (u)) user = identrx[2]; a = NULL; cbdone (); } void dnscb (ptr hh, int e) { h = hh; err = e; if (h && *h->h_name) host = h->h_name; cbdone (); } }; void identstat::cbdone () { if (--ncb) return; str res; if (user) res = user << "@" << host; else res = host; (*cb) (res, h, err); delete this; } void identptr (int fd, callback, int>::ref cb, unsigned timeout) { struct sockaddr_in la, ra; socklen_t len; len = sizeof (la); bzero (&la, sizeof (la)); bzero (&ra, sizeof (ra)); errno = 0; if (getsockname (fd, (struct sockaddr *) &la, &len) < 0 || la.sin_family != AF_INET || getpeername (fd, (struct sockaddr *) &ra, &len) < 0 || ra.sin_family != AF_INET || len != sizeof (la)) { warn ("ident: getsockname/getpeername: %s\n", strerror (errno)); (*cb) ("*disconnected*", NULL, ARERR_CANTSEND); return; } u_int lp = ntohs (la.sin_port); la.sin_port = htons (0); u_int rp = ntohs (ra.sin_port); ra.sin_port = htons (AUTH_PORT); int ifd = -1; if (timeout > 0) ifd = socket (AF_INET, SOCK_STREAM, 0); if (ifd >= 0) { close_on_exec (ifd); make_async (ifd); if (connect (ifd, (sockaddr *) &ra, sizeof (ra)) < 0 && errno != EINPROGRESS) { close (ifd); ifd = -1; } } identstat *is = New identstat; is->err = 0; is->cb = cb; is->host = inet_ntoa (ra.sin_addr); if (ifd >= 0) { is->ncb = 2; close_on_exec (ifd); is->a = aios::alloc (ifd); is->a << rp << ", " << lp << "\r\n"; is->a->settimeout (timeout); is->a->readline (wrap (is, &identstat::identcb)); } else is->ncb = 1; dns_hostbyaddr (ra.sin_addr, wrap (is, &identstat::dnscb)); } static void strip_hostent (callback::ref cb, str id, ptr h, int err) { (*cb) (id, err); } void ident (int fd, callback::ref cb, unsigned timeout) { identptr (fd, wrap (strip_hostent, cb), timeout); } avenger-0.8.5/libasync/tcpconnect.C0000644000175000017500000002021712260422177014151 00000000000000/* $Id$ */ /* * * Copyright (C) 2003 David Mazieres (dm@uun.org) * * 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 * */ #include "async.h" #include "dns.h" struct tcpconnect_t { virtual ~tcpconnect_t () {} }; struct tcpportconnect_t : tcpconnect_t { u_int16_t port; cbi cb; int fd; dnsreq_t *dnsp; str *namep; tcpportconnect_t (const in_addr &a, u_int16_t port, cbi cb); tcpportconnect_t (str hostname, u_int16_t port, cbi cb, bool dnssearch, str *namep); ~tcpportconnect_t (); void reply (int s) { if (s == fd) fd = -1; (*cb) (s); delete this; } void fail (int error) { errno = error; reply (-1); } void connect_to_name (str hostname, bool dnssearch); void name_cb (ptr h, int err); void connect_to_in_addr (const in_addr &a); void connect_cb (); }; tcpportconnect_t::tcpportconnect_t (const in_addr &a, u_int16_t p, cbi c) : port (p), cb (c), fd (-1), dnsp (NULL), namep (NULL) { connect_to_in_addr (a); } tcpportconnect_t::tcpportconnect_t (str hostname, u_int16_t p, cbi c, bool dnssearch, str *np) : port (p), cb (c), fd (-1), dnsp (NULL), namep (np) { connect_to_name (hostname, dnssearch); } tcpportconnect_t::~tcpportconnect_t () { if (dnsp) dnsreq_cancel (dnsp); if (fd >= 0) { fdcb (fd, selwrite, NULL); close (fd); } } void tcpportconnect_t::connect_to_name (str hostname, bool dnssearch) { dnsp = dns_hostbyname (hostname, wrap (this, &tcpportconnect_t::name_cb), dnssearch); } void tcpportconnect_t::name_cb (ptr h, int err) { dnsp = NULL; if (!h) { if (dns_tmperr (err)) fail (EAGAIN); else fail (ENOENT); return; } if (namep) *namep = h->h_name; connect_to_in_addr (*(in_addr *) h->h_addr); } void tcpportconnect_t::connect_to_in_addr (const in_addr &a) { sockaddr_in sin; bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (port); sin.sin_addr = a; fd = inetsocket (SOCK_STREAM); if (fd < 0) { delaycb (0, wrap (this, &tcpportconnect_t::fail, errno)); return; } make_async (fd); close_on_exec (fd); if (connect (fd, (sockaddr *) &sin, sizeof (sin)) < 0 && errno != EINPROGRESS) { delaycb (0, wrap (this, &tcpportconnect_t::fail, errno)); return; } fdcb (fd, selwrite, wrap (this, &tcpportconnect_t::connect_cb)); } void tcpportconnect_t::connect_cb () { fdcb (fd, selwrite, NULL); sockaddr_in sin; socklen_t sn = sizeof (sin); if (!getpeername (fd, (sockaddr *) &sin, &sn)) { reply (fd); return; } int err = 0; sn = sizeof (err); getsockopt (fd, SOL_SOCKET, SO_ERROR, (char *) &err, &sn); fail (err ? err : ECONNREFUSED); } tcpconnect_t * tcpconnect (in_addr addr, u_int16_t port, cbi cb) { return New tcpportconnect_t (addr, port, cb); } tcpconnect_t * tcpconnect (str hostname, u_int16_t port, cbi cb, bool dnssearch, str *namep) { return New tcpportconnect_t (hostname, port, cb, dnssearch, namep); } void tcpconnect_cancel (tcpconnect_t *tc) { delete tc; } struct tcpsrvconnect_t : tcpconnect_t { u_int16_t defport; cbi cb; int dnserr; dnsreq_t *areq; ptr h; dnsreq_t *srvreq; ptr srvl; timecb_t *tmo; vec cons; int cbad; int error; ptr *srvlp; str *namep; tcpsrvconnect_t (str name, str service, cbi cb, u_int16_t dp, bool search, ptr *sp, str *np); tcpsrvconnect_t (ref sl, cbi cb, str *np); ~tcpsrvconnect_t (); void dnsacb (ptr, int err); void dnssrvcb (ptr, int err); void maybe_start (int err); void connectcb (int cn, int fd); void nextsrv (bool timeout = false); }; void tcpsrvconnect_t::nextsrv (bool timeout) { if (!timeout) timecb_remove (tmo); tmo = NULL; u_int n = cons.size (); if (n >= srvl->s_nsrv) return; // warn ("nextsrv %d (port %d)\n", n, srvl->s_srvs[n].port); if (!srvl->s_srvs[n].port || !srvl->s_srvs[n].name[0]) { cons.push_back (NULL); errno = ENOENT; connectcb (n, -1); return; } else if (h && !strcasecmp (srvl->s_srvs[n].name, h->h_name)) cons.push_back (tcpconnect (*(in_addr *) h->h_addr, srvl->s_srvs[n].port, wrap (this, &tcpsrvconnect_t::connectcb, n))); else { str name = srvl->s_srvs[n].name; addrhint **hint; for (hint = srvl->s_hints; *hint && ((*hint)->h_addrtype != AF_INET || strcasecmp ((*hint)->h_name, name)); hint++) ; if (*hint) cons.push_back (tcpconnect (inaddr_cast ((*hint)->h_address), srvl->s_srvs[n].port, wrap (this, &tcpsrvconnect_t::connectcb, n))); else cons.push_back (tcpconnect (srvl->s_srvs[n].name, srvl->s_srvs[n].port, wrap (this, &tcpsrvconnect_t::connectcb, n), false)); } tmo = delaycb (4, wrap (this, &tcpsrvconnect_t::nextsrv, true)); } void tcpsrvconnect_t::connectcb (int cn, int fd) { cons[cn] = NULL; if (fd >= 0) { errno = 0; if (namep) { if (srvl) { *namep = srvl->s_srvs[cn].name; srvl->s_srvs[cn].port = 0; } else *namep = h->h_name; } (*cb) (fd); delete this; return; } // warn ("%s:%d %m\n", srvl->s_srvs[cn].name, srvl->s_srvs[cn].port); if (!error) error = errno; else if (errno == EAGAIN) error = errno; else if (error != EAGAIN && errno != ENOENT) error = errno; if (srvl) srvl->s_srvs[cn].port = 0; if (!srvl || ++cbad >= srvl->s_nsrv) { errno = error; (*cb) (-1); delete this; return; } if (!cons.back ()) nextsrv (); } tcpsrvconnect_t::tcpsrvconnect_t (str name, str s, cbi cb, u_int16_t dp, bool search, ptr *sp, str *np) : defport (dp), cb (cb), dnserr (0), tmo (NULL), cbad (0), error (0), srvlp (sp), namep (np) { areq = dns_hostbyname (name, wrap (this, &tcpsrvconnect_t::dnsacb), search); srvreq = dns_srvbyname (name, "tcp", s, wrap (this, &tcpsrvconnect_t::dnssrvcb), search); } tcpsrvconnect_t::tcpsrvconnect_t (ref sl, cbi cb, str *np) : defport (0), cb (cb), dnserr (0), areq (NULL), srvreq (NULL), tmo (NULL), cbad (0), error (0), srvlp (NULL), namep (np) { delaycb (0, wrap (this, &tcpsrvconnect_t::dnssrvcb, sl, 0)); } tcpsrvconnect_t::~tcpsrvconnect_t () { for (tcpconnect_t **cp = cons.base (); cp < cons.lim (); cp++) tcpconnect_cancel (*cp); dnsreq_cancel (areq); dnsreq_cancel (srvreq); timecb_remove (tmo); } void tcpsrvconnect_t::maybe_start (int err) { if (err && err != NXDOMAIN && err != ARERR_NXREC) { if (!dnserr) dnserr = err; else if (!dns_tmperr (dnserr) && dns_tmperr (err)) dnserr = err; } if (srvreq || (!srvl && areq)) return; if (srvl) nextsrv (); else if (h && defport) { cons.push_back (tcpconnect (*(in_addr *) h->h_addr, defport, wrap (this, &tcpsrvconnect_t::connectcb, 0))); } else { if (dns_tmperr (dnserr)) errno = EAGAIN; else errno = ENOENT; (*cb) (-1); delete this; } } void tcpsrvconnect_t::dnsacb (ptr hh, int err) { areq = NULL; h = hh; maybe_start (err); } void tcpsrvconnect_t::dnssrvcb (ptr s, int err) { srvreq = NULL; srvl = s; if (srvlp) *srvlp = srvl; maybe_start (err); } tcpconnect_t * tcpconnect_srv (str hostname, str service, u_int16_t defport, cbi cb, bool dnssearch, ptr *srvlp, str *np) { if (srvlp && *srvlp) return New tcpsrvconnect_t (*srvlp, cb, np); else return New tcpsrvconnect_t (hostname, service, cb, defport, dnssearch, srvlp, np); } tcpconnect_t * tcpconnect_srv_retry (ref srvl, cbi cb, str *np) { return New tcpsrvconnect_t (srvl, cb, np); } avenger-0.8.5/libasync/vec.h0000644000175000000120000001331112077217760012624 00000000000000// -*- c++ -*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _VECTOR_H_INCLUDED_ #define _VECTOR_H_INCLUDED_ 1 #include "opnew.h" #include "stllike.h" #include "array.h" #include "msb.h" template struct vec_base { typedef typename toarray(T) elm_t; protected: elm_t *basep; elm_t *firstp; elm_t *lastp; elm_t *limp; union { double alignment_hack; char defbuf_space[N * sizeof (elm_t)]; }; elm_t *def_basep () { return reinterpret_cast (defbuf_space); } elm_t *def_limp () { return def_basep () + N; } void bfree (T *t) { if ( t != def_basep ()) xfree (t); } }; template struct vec_base { typedef typename toarray(T) elm_t; protected: elm_t *basep; elm_t *firstp; elm_t *lastp; elm_t *limp; elm_t *def_basep () { return NULL; } elm_t *def_limp () { return NULL; } void bfree (T *t) { xfree (t); } public: #define doswap(x) tmp = x; x = v.x; v.x = tmp void swap (vec_base &v) { elm_t *tmp; doswap (basep); doswap (firstp); doswap (lastp); doswap (limp); }; #undef doswap }; template class vec : public vec_base { protected: typedef vec_base base_t; typedef typename base_t::elm_t elm_t; using base_t::basep; using base_t::firstp; using base_t::lastp; using base_t::limp; using base_t::def_basep; using base_t::def_limp; void move (elm_t *dst) { if (dst == firstp) return; assert (dst < firstp || dst >= lastp); basep = dst; for (elm_t *src = firstp; src < lastp; src++) { new ((void *) (dst++)) elm_t (*src); src->~elm_t (); } lastp = basep + (lastp - firstp); firstp = basep; } static elm_t &construct (elm_t &e) { return *new (implicit_cast (&e)) elm_t; } static elm_t &cconstruct (elm_t &e, const elm_t &v) { return *new (implicit_cast (&e)) elm_t (v); } static void destroy (elm_t &e) { e.~elm_t (); } void init () { lastp = firstp = basep = def_basep (); limp = def_limp (); } void del () { while (firstp < lastp) firstp++->~elm_t (); this->bfree (basep); } #define append(v) \ do { \ reserve (v.size ()); \ for (const elm_t *s = v.base (), *e = v.lim (); s < e; s++) \ cconstruct (*lastp++, *s); \ } while (0) #ifdef CHECK_BOUNDS #define zcheck() assert (lastp > firstp) #define bcheck(n) assert ((size_t) (n) < (size_t) (lastp - firstp)) #define pcheck(n) assert ((size_t) (n) <= (size_t) (lastp - firstp)) #else /* !CHECK_BOUNDS */ #define zcheck() #define bcheck(n) #define pcheck(n) #endif /* !CHECK_BOUNDS */ public: vec () { init (); } vec (const vec &v) { init (); append (v); } template vec (const vec &v) { init (); append (v); } ~vec () { del (); } void clear () { del (); init (); } vec &operator= (const vec &v) { if (this != &v) { clear (); append (v); } return *this; } template vec &operator= (const vec &v) { clear (); append (v); return *this; } void reserve (size_t n) { if (lastp + n <= limp) return; size_t nalloc = limp - basep; size_t nwanted = lastp - firstp + n; if (nwanted > nalloc / 2) { nalloc = 1 << fls (max (nalloc, nwanted)); elm_t *obasep = basep; move (static_cast (txmalloc (nalloc * sizeof (elm_t)))); limp = basep + nalloc; this->bfree (obasep); } else move (basep); } void setsize (size_t n) { size_t s = size (); if (n < s) popn_back (s - n); else if ((n -= s)) { reserve (n); elm_t *sp = lastp; lastp += n; while (sp < lastp) construct (*sp++); } } elm_t *base () { return firstp; } const elm_t *base () const { return firstp; } elm_t *lim () { return lastp; } const elm_t *lim () const { return lastp; } size_t size () const { return lastp - firstp; } bool empty () const { return lastp == firstp; } elm_t &front () { zcheck (); return *firstp; } const elm_t &front () const { zcheck (); return *firstp; } elm_t &back () { zcheck (); return lastp[-1]; } const elm_t &back () const { zcheck (); return lastp[-1]; } elm_t &operator[] (ptrdiff_t i) { bcheck (i); return firstp[i]; } const elm_t &operator[] (ptrdiff_t i) const { bcheck (i); return firstp[i]; } elm_t &push_back () { reserve (1); return construct (*lastp++); } elm_t &push_back (const elm_t &e) { reserve (1); return cconstruct (*lastp++, e); } elm_t pop_back () { zcheck (); return destroy_return (*--lastp); } void popn_back (size_t n) { pcheck (n); elm_t *sp = lastp; lastp -= n; while (sp > lastp) destroy (*--sp); } elm_t pop_front () { zcheck (); return destroy_return (*firstp++); } void popn_front (size_t n) { pcheck (n); elm_t *sp = firstp; firstp += n; while (sp < firstp) destroy (*sp++); } #undef zcheck #undef bcheck #undef pcheck #undef append }; template void swap (vec &a, vec &b) { a.swap (b); } #endif /* !_VECTOR_H_INCLUDED_ */ avenger-0.8.5/libasync/backoff.h0000644000175000017500000000547111221237220013443 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _BACKOFF_H_ #define _BACKOFF_H_ 1 template #ifndef NO_TEMPLATE_FRIENDS class #else /* NO_TEMPLATE_FRIENDS */ struct #endif /* NO_TEMPLATE_FRIENDS */ tmoq_entry { u_int qno; time_t tm; T *next; T **pprev; public: tmoq_entry () : qno ((u_int) -1) {} #ifndef NO_TEMPLATE_FRIENDS template U::*field, u_int minto, u_int maxsend> friend class tmoq; #endif /* NO_TEMPLATE_FRIENDS */ }; template T::*field, u_int minto = 2, u_int maxsend = 5> class tmoq { struct head { T *first; T **plast; head () {first = NULL; plast = &first;} }; head queue[maxsend]; bool pending[maxsend]; static void tcb (tmoq *tq, u_int qn) { tq->pending[qn] = false; tq->runq (qn); tq->schedq (qn); } void schedq (u_int qn) { T *p; if (!pending[qn] && (p = queue[qn].first)) { pending[qn] = true; timecb ((p->*field).tm, wrap (tcb, this, qn)); } } void runq (u_int qn) { time_t now = time (NULL); T *p; while ((p = queue[qn].first) && (p->*field).tm <= now) { remove (p); if (qn < maxsend - 1) insert (p, qn + 1, now); else { (p->*field).qno = maxsend; p->timeout (); } } } void insert (T *p, u_int qn, time_t now = 0) { (p->*field).qno = qn; (p->*field).tm = (now ? now : time (NULL)) + (minto << qn); (p->*field).next = NULL; (p->*field).pprev = queue[qn].plast; *queue[qn].plast = p; queue[qn].plast = &(p->*field).next; schedq (qn); p->xmit (qn); } public: tmoq () { for (size_t i = 0; i < maxsend; i++) pending[i] = false; } void start (T *p) { insert (p, 0); } void keeptrying (T *p) { assert ((p->*field).qno >= maxsend); insert (p, maxsend - 1); } void remove (T *p) { if ((p->*field).qno < maxsend) { if ((p->*field).next) ((p->*field).next->*field).pprev = (p->*field).pprev; else queue[(p->*field).qno].plast = (p->*field).pprev; *(p->*field).pprev = (p->*field).next; } } }; #endif /* !_BACKOFF_H_ */ avenger-0.8.5/libasync/cbuf.h0000644000175000017500000000445311221237220012766 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_CBUF_H_ #define _ASYNC_CBUF_H_ 1 #include "sysconf.h" class cbuf { char *buf; size_t buflen; bool empty; size_t start; size_t end; iovec inv[2]; iovec outv[2]; public: cbuf (size_t n) : buf ((char *) xmalloc (n)), buflen (n), empty (true), start (0), end (0) {} ~cbuf () { xfree (buf); } void resize (size_t n); void clear () { empty = false; start = end = 0; } size_t space () const { return (empty || start < end ? buflen : 0) + start - end; } size_t bytes () const { return buflen - space (); } const iovec *iniov (); int iniovcnt () { return empty || start < end ? 1 + !!start : start != end; } void addbytes (size_t n); size_t size () const { return (empty || start < end ? 0 : buflen) + end - start; } char &at (size_t n) const { assert (n < size ()); return buf[(n + start) % buflen]; } char &operator[] (ptrdiff_t n) const { return at (n); } int find (char c); const iovec *outiov (); int outiovcnt () { if (empty) return 0; if (start < end) return 1; else return 1 + !!end; } void rembytes (size_t n) { if (n) { assert (n <= size ()); start = (start + n) % buflen; empty = start == end; } } void unrembytes (size_t n) { if (n) { assert (n <= space ()); start = (start >= n ? 0 : buflen) + start - n; empty = false; } } void copyout (void *_dst, size_t len); private: cbuf (const cbuf &c); cbuf &operator= (const cbuf &c); }; #endif /* !_ASYNC_CBUF_H_ */ avenger-0.8.5/libasync/union.h0000644000175000017500000001261111221237220013172 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ARPC_TAGUNION_INCLUDED_ #define _ARPC_TAGUNION_INCLUDED_ 1 #include "opnew.h" #include "array.h" #include #ifndef TUNION_DEBUG # if defined (CHECK_BOUNDS) || defined (DMALLOC) # define TUNION_DEBUG 1 # endif /* CHECK_BOUNDS || DMALLOC */ #endif /* !TUNION_DEBUG */ #if 0 /* For a contant n, C++ defines sizeof (T[n]) to be n * sizeof (T). * Assuming 8 is the maximum alignment requirement, this means any * object T's maximum alignment requirment is sizeof (T) % 8. * AlignmentHack (T) can be used to declare a primitive type with the * same alignment requirements. */ template struct __alignment_hack; template<> struct __alignment_hack<0> { typedef double type; }; template<> struct __alignment_hack<1> { typedef char type; }; template<> struct __alignment_hack<2> { typedef u_int16_t type; }; template<> struct __alignment_hack<3> { typedef char type; }; template<> struct __alignment_hack<4> { typedef u_int32_t type; }; template<> struct __alignment_hack<5> { typedef char type; }; template<> struct __alignment_hack<6> { typedef u_int16_t type; }; template<> struct __alignment_hack<7> { typedef char type; }; #define AlignmentHack(T) typename ::__alignment_hack<(sizeof(T)%8)>::type #else #define AlignmentHack(T) u_int64_t #endif class union_entry_base { protected: struct vtbl { const std::type_info *type; void (*destructor) (union_entry_base *); void (*assignop) (union_entry_base *, const union_entry_base *); size_t size; }; const vtbl *vptr; public: void init () { vptr = NULL; } void init (const union_entry_base &b) { init (); assign (b); } void destroy () { if (vptr) vptr->destructor (this); init (); } void assign (const union_entry_base &b) { if (b.vptr) b.vptr->assignop (this, &b); else destroy (); } const std::type_info *type () const { return vptr ? vptr->type : NULL; } }; template class union_entry : public union_entry_base { union { AlignmentHack(T) _hack; char m[sizeof (T)]; }; static const vtbl *getvptr () { static const vtbl vt = { &typeid (T), &destructor, &assignop, sizeof (T) }; return &vt; } static void destructor (union_entry_base *tb) { union_entry *te = static_cast (tb); te->_addr ()->~T (); } static void assignop (union_entry_base *dstb, const union_entry_base *srcb) { union_entry *dst = static_cast (dstb); const union_entry *src = static_cast (srcb); dst->select (); (void) (*dst->_addr () = *src->_addr ()); // XXX - cast required by egcs } T *_addr () { return reinterpret_cast (m); } const T *_addr () const { return reinterpret_cast (m); } void verify () const { #if TUNION_DEBUG if (!vptr || *vptr->type != typeid (T)) panic ("union_entry<%s>::verify: accessed when %s selected\n", typeid (T).name (), vptr ? vptr->type->name () : "NULL"); #endif /* TUNION_DEBUG */ } public: T *addr () { verify (); return _addr (); } const T *addr () const { verify (); return _addr (); } T *operator-> () { return addr (); } const T *operator-> () const { return addr (); } T &operator *() { return *addr (); } const T &operator *() const { return *addr (); } operator T *() { return addr (); } operator const T *() const { return addr (); } void select () { if (!vptr || *vptr->type != typeid (T)) { destroy (); vptr = getvptr (); new (static_cast (m)) T; } } void Xstompcast () { #if TUNION_DEBUG if (!vptr || vptr->size != sizeof (T)) panic ("union_entry<%s>::Xstompcast: cast changes object size\n", typeid (T).name ()); #endif /* TUNION_DEBUG */ vptr = getvptr (); } }; template<> class union_entry : public union_entry_base { static const vtbl *getvptr () { static const vtbl vt = { &typeid (void), &destructor, &assignop, 0 }; return &vt; } static void destructor (union_entry_base *tb) {} static void assignop (union_entry_base *dstb, const union_entry_base *srcb) { union_entry *dst = static_cast (dstb); dst->select (); } public: void select () { if (!vptr || *vptr->type != typeid (void)) { destroy (); vptr = getvptr (); } } /* It's okay to cast anything to void. */ void Xstompcast () { select (); } }; template class union_entry : public union_entry { // typedef toarray (T[n]) array_t; typename toarray (T) &operator[] (ptrdiff_t i) { return (**this)[i]; } const typename toarray (T) &operator[] (ptrdiff_t i) const { return (**this)[i]; } }; #endif /* !_ARPC_TAGUNION_INCLUDED_ */ avenger-0.8.5/libasync/convertint.C0000644000175000017500000001235211221237220014172 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "parseopt.h" /*- * Copyright (c) 1992 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Convert a string to a quad integer. * * Ignores `locale' stuff. Assumes that the upper and lower case * alphabets and digits are each contiguous. */ int64_t strtoi64 (const char *nptr, char **endptr, register int base) { register const char *s; register int64_t acc, cutoff; register int c; register int neg, any, cutlim; /* * Skip white space and pick up leading +/- sign if any. * If base is 0, allow 0x for hex and 0 for octal, else * assume decimal; if base is already 16, allow 0x. */ s = nptr; do { c = (unsigned char) *s++; } while (isspace(c)); if (c == '-') { neg = 1; c = *s++; } else { neg = 0; if (c == '+') c = *s++; } if ((base == 0 || base == 16) && c == '0' && (*s == 'x' || *s == 'X')) { c = s[1]; s += 2; base = 16; } if (base == 0) base = c == '0' ? 8 : 10; /* * Compute the cutoff value between legal numbers and illegal * numbers. That is the largest legal value, divided by the * base. An input number that is greater than this value, if * followed by a legal input character, is too big. One that * is equal to this value may be valid or not; the limit * between valid and invalid numbers is then based on the last * digit. For instance, if the range for quads is * [-9223372036854775808..9223372036854775807] and the input base * is 10, cutoff will be set to 922337203685477580 and cutlim to * either 7 (neg==0) or 8 (neg==1), meaning that if we have * accumulated a value > 922337203685477580, or equal but the * next digit is > 7 (or 8), the number is too big, and we will * return a range error. * * Set any if any `digits' consumed; make it negative to indicate * overflow. */ cutoff = neg ? -INT64(0x7fffffffffffffff) - 1 : INT64(0x7fffffffffffffff); cutlim = cutoff % base; cutoff /= base; if (neg) { if (cutlim > 0) { cutlim -= base; cutoff += 1; } cutlim = -cutlim; } for (acc = 0, any = 0;; c = (unsigned char) *s++) { if (isdigit(c)) c -= '0'; else if (isalpha(c)) c -= isupper(c) ? 'A' - 10 : 'a' - 10; else break; if (c >= base) break; if (any < 0) continue; if (neg) { if (acc < cutoff || (acc == cutoff && c > cutlim)) { any = -1; acc = - INT64(0x7fffffffffffffff) - 1; //errno = ERANGE; } else { any = 1; acc *= base; acc -= c; } } else { if (acc > cutoff || (acc == cutoff && c > cutlim)) { any = -1; acc = INT64(0x7fffffffffffffff); //errno = ERANGE; } else { any = 1; acc *= base; acc += c; } } } if (endptr != 0) *endptr = (char *) (any ? s - 1 : nptr); return (acc); } avenger-0.8.5/libasync/pipe2str.C0000644000175000017500000000312311221237220013543 00000000000000/* $Id$ */ /* * * Copyright (C) 2002 David Mazieres (dm@uun.org) * * 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 * */ #include "async.h" void pipe2str (int fd, cbs cb, int *fdp, strbuf *sb) { if (!sb) { sb = New strbuf (); make_async (fd); fdcb (fd, selread, wrap (pipe2str, fd, cb, fdp, sb)); } int n; if (fdp && *fdp < 0) { char *buf = sb->tosuio ()->getspace (8192); n = readfd (fd, buf, 8192, fdp); if (n > 0) sb->tosuio ()->print (buf, n); } else n = sb->tosuio ()->input (fd); if (!n) (*cb) (*sb); else if (n < 0 && errno != EAGAIN) (*cb) (NULL); else return; fdcb (fd, selread, NULL); close (fd); delete sb; } void chldrun (cbi chld, cbs cb) { int fds[2]; if (pipe (fds) < 0) (*cb) (NULL); switch (afork ()) { case -1: (*cb) (NULL); return; case 0: close (fds[0]); (*chld) (fds[1]); _exit (0); } close (fds[1]); pipe2str (fds[0], cb); } avenger-0.8.5/libasync/rxx.C0000644000175000017500000001073311221237220012621 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "rxx.h" #include "amisc.h" struct rcbase { enum { magicval = int (0xa5e10288) }; int32_t cnt; int32_t magic; }; void * rcmalloc (size_t n) { rcbase *r = static_cast (xmalloc (sizeof (rcbase) + n)); r->cnt = 1; r->magic = rcbase::magicval; // warn ("alloc %p\n", r); return r + 1; } void rcfree (void *p) { if (p) { rcbase *r = static_cast (p) - 1; assert (r->magic == rcbase::magicval); if (!--r->cnt) { // warn ("free %p\n", r); r->magic = 0; xfree (r); } else assert (r->cnt > 0); } } void * rccopy (void *p) { if (p) { rcbase *r = static_cast (p) - 1; assert (r->magic == rcbase::magicval); r->cnt++; } return p; } int rxxinit::count; void rxxinit::start () { pcre_malloc = rcmalloc; pcre_free = rcfree; } void rxxinit::stop () { } str rxx::init (const char *pat, const char *opt) { extra = NULL; nsubpat = 0; ovector = NULL; bool studyit = false; int options = 0; for (; *opt; opt++) switch (*opt) { case '^': options |= PCRE_ANCHORED; break; case 'i': options |= PCRE_CASELESS; break; case 's': options |= PCRE_DOTALL; break; case 'm': options |= PCRE_MULTILINE; break; case 'x': options |= PCRE_EXTENDED; break; case 'U': options |= PCRE_UNGREEDY; break; case 'X': options |= PCRE_EXTRA; break; case 'S': studyit = true; break; default: return strbuf ("invalid regular expression option '%c'\n", *opt); } const char *errptr; int erroffset; re = pcre_compile (pat, options, &errptr, &erroffset, NULL); if (!re) { strbuf err; err << "Invalid regular expression:\n" << " " << pat << "\n"; suio_fill (err.tosuio (), ' ', erroffset); err << " ^\n" << errptr << ".\n"; return err; } if (studyit) { str err = study (); if (err) return strbuf () << "Could not study regular expression: " << err; } int ns = pcre_info (re, NULL, NULL); assert (ns >= 0); ovecsize = (ns + 1) * 3; return NULL; } void rxx::_exec (const char *p, size_t len, int options) { subj = NULL; if (!ovector) ovector = New int[ovecsize]; nsubpat = pcre_exec (re, extra, p, len, 0, options, ovector, ovecsize); if (nsubpat <= 0 && nsubpat != PCRE_ERROR_NOMATCH) panic ("rxx/pcre_exec error %d\n", nsubpat); } void rxx::exec (str s, int options) { subj = s; if (!ovector) ovector = New int[ovecsize]; nsubpat = pcre_exec (re, extra, s.cstr (), s.len (), 0, options, ovector, ovecsize); if (nsubpat <= 0 && nsubpat != PCRE_ERROR_NOMATCH) panic ("rxx/pcre_exec error %d\n", nsubpat); } str rxx::at (ptrdiff_t n) const { assert (n >= 0); if (n >= nsubpat) return NULL; size_t i = 2 * n; if (ovector[i] == -1) return NULL; return str (subj.cstr () + ovector[i], ovector[i+1] - ovector[i]); } rxx & rxx::operator= (const rxx &r) { if (&r != this) { this->~rxx (); copy (r); } return *this; } int split (vec *out, rxx pat, str expr, size_t lim, bool emptylast) { const char *p = expr; const char *const e = p + expr.len (); size_t n; if (out) out->clear (); for (n = 0; n + 1 < lim; n++) { pat._exec (p, e - p, 0); if (!pat.success ()) break; if (out) out->push_back (str (p, pat.start (0))); p += max (pat.end (0), 1); } if (lim && (p < e || emptylast)) { n++; if (out) out->push_back (str (p, e - p)); } return n; } str join (str sep, const vec &v) { strbuf sb; const str *sp = v.base (); if (sp < v.lim ()) { sb.cat (*sp++); while (sp < v.lim ()) sb.cat (sep).cat (*sp++); } return sb; } avenger-0.8.5/libasync/suio++.C0000644000175000017500000002531411221237220013106 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "suio++.h" #ifdef DMALLOC /* Simple, IP-like checksum */ static u_int16_t cksum (const void *_data, int len) { const u_char *data = static_cast (_data); union { u_char b[2]; u_int16_t w; } bwu; u_int32_t sum; const u_char *end; if (!len) return 0; bwu.w = 0; if ((u_long) data & 1) { bwu.b[0] = *data; sum = cksum ((char *) data + 1, len - 1); sum = ((sum >> 8) & 0xff) | ((sum & 0xff) << 8); sum += bwu.w; len = 1; } else sum = 0; end = data + (len & ~1); while (data < end) { sum += *(u_int16_t*) data; data += sizeof (u_int16_t); } if (len & 1) { bwu.b[0] = *data; sum += bwu.w; } return ~sum; } struct suio_check_dat { const void *buf; size_t len; u_int16_t sum; const char *line; }; static void suio_docheck (suio_check_dat d) { if (cksum (d.buf, d.len) != d.sum) panic ("%s: data in suio subsquently changed!\n", d.line); } void __suio_check (const char *line, suio *uio, const void *buf, size_t len) { suio_check_dat d = { buf, len, cksum (buf, len), line }; uio->iovcb (wrap (suio_docheck, d)); } void __suio_printcheck (const char *line, suio *uio, const void *buf, size_t len) { static bool do_check = dmalloc_debug_current () & 0x200000; // free-blank uio->print (buf, len); if (do_check) { suio_check_dat d = { buf, len, cksum (buf, len), line }; uio->iovcb (wrap (suio_docheck, d)); } } #endif /* DMALLOC */ size_t iovsize (const iovec *iov, int cnt) { const iovec *end = iov + cnt; size_t size = 0; while (iov < end) size += iov++->iov_len; return size; } iovmgr::iovmgr (const iovec *v, int iovcnt) : iov (v), lim (iov + iovcnt) { if (iov < lim) cur = *iov++; else { iov = lim = NULL; cur.iov_base = NULL; cur.iov_len = 0; } } void iovmgr::skip (size_t n) { if (n < implicit_cast (cur.iov_len)) { cur.iov_base = (char *) cur.iov_base + n; cur.iov_len -= n; return; } n -= cur.iov_len; while (iov < lim && n >= implicit_cast (iov->iov_len)) n -= iov++->iov_len; if (n) { if (iov == lim || n > implicit_cast (iov->iov_len)) panic ("iovmgr: skip value larger than iovsize\n"); cur.iov_base = (char *) iov->iov_base + n; cur.iov_len = iov->iov_len - n; iov++; } else { cur.iov_base = NULL; cur.iov_len = 0; } } size_t iovmgr::copyout (char *buf, size_t len) { if (len < implicit_cast (cur.iov_len)) { memcpy (buf, cur.iov_base, len); cur.iov_base = (char *) cur.iov_base + len; cur.iov_len -= len; return len; } memcpy (buf, cur.iov_base, cur.iov_len); char *cp = buf + cur.iov_len; char *eom = buf + len; while (iov < lim && implicit_cast (iov->iov_len) <= (size_t) (eom - cp)) { memcpy (cp, iov->iov_base, iov->iov_len); cp += iov++->iov_len; } if (iov == lim) { cur.iov_base = NULL; cur.iov_len = 0; } else if (cp < eom) { size_t n = eom - cp; memcpy (cp, iov->iov_base, n); cp += n; cur.iov_base = (char *) iov->iov_base + n; cur.iov_len = iov->iov_len - n; iov++; } else cur = *iov++; return cp - buf; } size_t iovmgr::size () const { size_t n = cur.iov_len; for (const iovec *v = iov; v < lim; v++) n += v->iov_len; return n; } void suio::makeuiocbs () { callback::ptr cb; while (!uiocbs.empty () && uiocbs.front ().nbytes <= nrembytes) { // it is safer to pop first, and then call. cb = uiocbs.pop_front ().cb; (*cb) (); } } suio::suio () : uiobytes (0), nrembytes (0), nremiov (0), lastiovend (NULL), scratch_buf (defbuf), scratch_pos (defbuf), scratch_lim (defbuf + sizeof (defbuf)), allocator (default_allocator), deallocator (default_deallocator) { } suio::~suio () { clear (); } void suio::clear () { rembytes (resid ()); /* XXX - GCC BUG: To help derived classes work around compiler * bugs, we actually must clear all memory associated with the suio * structure. Gcc often fails to call the destructor, so calling * clear should be a viable workaround. */ if (scratch_buf != defbuf) { deallocator (scratch_buf, scratch_lim - scratch_buf); scratch_buf = defbuf; scratch_lim = defbuf + sizeof (defbuf); } scratch_pos = defbuf; iovs.clear (); uiocbs.clear (); } void suio::condemn_scratch () { if (scratch_buf != defbuf) iovcb (wrap (deallocator, scratch_buf, scratch_lim - scratch_buf)); } char * suio::morescratch (size_t size) { size = ((size + MALLOCRESV + (blocksize - 1)) & ~(blocksize - 1)) - MALLOCRESV; condemn_scratch (); scratch_buf = scratch_pos = static_cast (allocator (size)); scratch_lim = scratch_buf + size; return scratch_buf; } void suio::slowfill (char c, size_t len) { size_t n = scratch_lim - scratch_pos; if (len <= n) { memset (scratch_pos, c, len); pushiov (scratch_pos, len); } else { if (n >= smallbufsize || scratch_pos == lastiovend) { memset (scratch_pos, c, n); pushiov (scratch_pos, n); len -= n; } morescratch (len); memset (scratch_pos, c, len); pushiov (scratch_pos, len); } } void suio::slowcopy (const void *_buf, size_t len) { const char *buf = static_cast (_buf); size_t n = scratch_lim - scratch_pos; if (len <= n) { memcpy (scratch_pos, buf, len); pushiov (scratch_pos, len); } else { if (n >= smallbufsize || scratch_pos == lastiovend) { memcpy (scratch_pos, buf, n); pushiov (scratch_pos, n); buf += n; len -= n; } morescratch (len); memcpy (scratch_pos, buf, len); pushiov (scratch_pos, len); } } void suio::copyv (const iovec *iov, size_t cnt, size_t skip) { iovmgr iom (iov, cnt); iom.skip (skip); size_t n = scratch_lim - scratch_pos; if (scratch_pos == lastiovend || n >= smallbufsize) { size_t m = iom.copyout (scratch_pos, scratch_lim - scratch_pos); if (m > 0) pushiov (scratch_pos, m); } n = iom.size (); if (n > 0) { morescratch (n); iom.copyout (scratch_pos, n); pushiov (scratch_pos, n); } } void suio::take (suio *uio) { int64_t bdiff = nrembytes + uiobytes - uio->nrembytes; // MK 2/13/2009: Here's the fix we wanted. The uiocbs stuff does // do the right thing when one suio takes another's payload, but // there was an off-by-one error with the scratch buffer that's // currently in use by uio. We have to make sure that it gets // cleaned up too! uio->condemn_scratch (); uio->nrembytes += uio->uiobytes; uio->nremiov += uio->iovs.size (); uio->uiobytes = 0; for (iovec *v = uio->iovs.base (), *e = uio->iovs.lim (); v < e; v++) if (v->iov_base >= uio->defbuf && v->iov_base < uio->defbuf + sizeof (uio->defbuf)) copy (v->iov_base, v->iov_len); else pushiov (v->iov_base, v->iov_len); uio->iovs.clear (); for (uiocb *c = uio->uiocbs.base (), *e = uio->uiocbs.lim (); c < e; c++) uiocbs.push_back (uiocb (c->nbytes + bdiff, c->cb)); uio->uiocbs.clear (); uio->scratch_buf = uio->scratch_pos = uio->defbuf; uio->scratch_lim = uio->defbuf + sizeof (uio->defbuf); } void suio::rembytes (size_t n) { assert (n <= uiobytes); // error to remove more than we have uiobytes -= n; nrembytes += n; iovec *iov = iovs.base (), *end = iovs.lim (); while (iov < end && n >= implicit_cast (iov->iov_len)) n -= iov++->iov_len; if (n > 0) { assert (iov < end); // else uiobytes was incorrect iov->iov_base = static_cast (iov->iov_base) + n; iov->iov_len -= n; } size_t niov = iov - iovs.base (); iovs.popn_front (niov); nremiov += niov; if (iovs.empty ()) { scratch_pos = scratch_buf; lastiovend = NULL; } makeuiocbs (); } int suio::output (int fd, int cnt) { u_int64_t startpos = nrembytes; ssize_t n = 0; if (cnt < 0) while (!iovs.empty () && (n = writev (fd, const_cast (iov ()), min (iovcnt (), (size_t) UIO_MAXIOV))) > 0) rembytes (n); else { assert ((size_t) cnt <= iovs.size ()); u_int64_t maxiovno = nremiov + cnt; while (nremiov < maxiovno && (n = writev (fd, const_cast (iov ()), min(maxiovno - nremiov, (u_int64_t) UIO_MAXIOV))) > 0) rembytes (n); } if (n < 0 && errno != EAGAIN) return -1; return nrembytes > startpos; } size_t suio::copyout (void *_buf, size_t len) const { char *buf = static_cast (_buf); char *cp = buf; for (const iovec *v = iov (), *e = iovlim (); v < e; v++) { if (len >= implicit_cast (v->iov_len)) { memcpy (cp, v->iov_base, v->iov_len); cp += v->iov_len; len -= v->iov_len; } else { memcpy (cp, v->iov_base, len); return cp - buf + len; } } return cp - buf; } int suio::input (int fd, size_t len) { size_t space = scratch_lim - scratch_pos; if (len <= space || !space) { void *buf = getspace (len); ssize_t n = read (fd, buf, len); if (n > 0) pushiov (buf, n); return n; } size_t size = ((len - space + MALLOCRESV + (blocksize - 1)) & ~(blocksize - 1)) - MALLOCRESV; char *buf = static_cast (allocator (size)); iovec iov[2]; iov[0].iov_base = scratch_pos; iov[0].iov_len = space; iov[1].iov_base = buf; iov[1].iov_len = len - space; ssize_t n = readv (fd, iov, 2); if (n > 0 && (size_t) n > space) { pushiov (iov[0].iov_base, iov[0].iov_len); assert (scratch_pos == scratch_lim); condemn_scratch (); scratch_pos = scratch_buf = buf; scratch_lim = buf + size; pushiov (scratch_pos, n - space); } else { if (n > 0) pushiov (iov[0].iov_base, n); deallocator (buf, size); } return n; } #ifndef DMALLOC char * suio_flatten (const struct suio *uio) #else /* DMALLOC */ char * __suio_flatten (const struct suio *uio, const char *file, int line) #endif /* DMALLOC */ { #ifndef DMALLOC char *buf = (char *) xmalloc (uio->resid ()); #else /* DMALLOC */ char *buf = (char *) _xmalloc_leap (file, line, uio->resid ()); #endif /* DMALLOC */ uio->copyout (buf); return buf; } avenger-0.8.5/libasync/study.c0000644000175000017500000003245513357041236013231 00000000000000/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* This is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. See the file Tech.Notes for some information on the internals. Written by: Philip Hazel Copyright (c) 1997-2003 University of Cambridge ----------------------------------------------------------------------------- Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software 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. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), then the terms of that licence shall supersede any condition above with which it is incompatible. ----------------------------------------------------------------------------- */ /* Include the internals header, which itself includes Standard C headers plus the external pcre header. */ #include "internal.h" /************************************************* * Set a bit and maybe its alternate case * *************************************************/ /* Given a character, set its bit in the table, and also the bit for the other version of a letter if we are caseless. Arguments: start_bits points to the bit map c is the character caseless the caseless flag cd the block with char table pointers Returns: nothing */ static void set_bit(uschar *start_bits, int c, BOOL caseless, compile_data *cd) { start_bits[c/8] |= (1 << (c&7)); if (caseless && (cd->ctypes[c] & ctype_letter) != 0) start_bits[cd->fcc[c]/8] |= (1 << (cd->fcc[c]&7)); } /************************************************* * Create bitmap of starting chars * *************************************************/ /* This function scans a compiled unanchored expression and attempts to build a bitmap of the set of initial characters. If it can't, it returns FALSE. As time goes by, we may be able to get more clever at doing this. Arguments: code points to an expression start_bits points to a 32-byte table, initialized to 0 caseless the current state of the caseless flag utf8 TRUE if in UTF-8 mode cd the block with char table pointers Returns: TRUE if table built, FALSE otherwise */ static BOOL set_start_bits(const uschar *code, uschar *start_bits, BOOL caseless, BOOL utf8, compile_data *cd) { register int c; /* This next statement and the later reference to dummy are here in order to trick the optimizer of the IBM C compiler for OS/2 into generating correct code. Apparently IBM isn't going to fix the problem, and we would rather not disable optimization (in this module it actually makes a big difference, and the pcre module can use all the optimization it can get). */ volatile int dummy __attribute__((unused)); do { const uschar *tcode = code + 1 + LINK_SIZE; BOOL try_next = TRUE; while (try_next) { /* If a branch starts with a bracket or a positive lookahead assertion, recurse to set bits from within them. That's all for this branch. */ if ((int)*tcode >= OP_BRA || *tcode == OP_ASSERT) { if (!set_start_bits(tcode, start_bits, caseless, utf8, cd)) return FALSE; try_next = FALSE; } else switch(*tcode) { default: return FALSE; /* Skip over callout */ case OP_CALLOUT: tcode += 2; break; /* Skip over extended extraction bracket number */ case OP_BRANUMBER: tcode += 3; break; /* Skip over lookbehind and negative lookahead assertions */ case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: do tcode += GET(tcode, 1); while (*tcode == OP_ALT); tcode += 1+LINK_SIZE; break; /* Skip over an option setting, changing the caseless flag */ case OP_OPT: caseless = (tcode[1] & PCRE_CASELESS) != 0; tcode += 2; break; /* BRAZERO does the bracket, but carries on. */ case OP_BRAZERO: case OP_BRAMINZERO: if (!set_start_bits(++tcode, start_bits, caseless, utf8, cd)) return FALSE; dummy = 1; do tcode += GET(tcode,1); while (*tcode == OP_ALT); tcode += 1+LINK_SIZE; break; /* Single-char * or ? sets the bit and tries the next item */ case OP_STAR: case OP_MINSTAR: case OP_QUERY: case OP_MINQUERY: set_bit(start_bits, tcode[1], caseless, cd); tcode += 2; #ifdef SUPPORT_UTF8 if (utf8) while ((*tcode & 0xc0) == 0x80) tcode++; #endif break; /* Single-char upto sets the bit and tries the next */ case OP_UPTO: case OP_MINUPTO: set_bit(start_bits, tcode[3], caseless, cd); tcode += 4; #ifdef SUPPORT_UTF8 if (utf8) while ((*tcode & 0xc0) == 0x80) tcode++; #endif break; /* At least one single char sets the bit and stops */ case OP_EXACT: /* Fall through */ tcode++; case OP_CHARS: /* Fall through */ tcode++; case OP_PLUS: case OP_MINPLUS: set_bit(start_bits, tcode[1], caseless, cd); try_next = FALSE; break; /* Single character type sets the bits and stops */ case OP_NOT_DIGIT: for (c = 0; c < 32; c++) start_bits[c] |= ~cd->cbits[c+cbit_digit]; try_next = FALSE; break; case OP_DIGIT: for (c = 0; c < 32; c++) start_bits[c] |= cd->cbits[c+cbit_digit]; try_next = FALSE; break; case OP_NOT_WHITESPACE: for (c = 0; c < 32; c++) start_bits[c] |= ~cd->cbits[c+cbit_space]; try_next = FALSE; break; case OP_WHITESPACE: for (c = 0; c < 32; c++) start_bits[c] |= cd->cbits[c+cbit_space]; try_next = FALSE; break; case OP_NOT_WORDCHAR: for (c = 0; c < 32; c++) start_bits[c] |= ~cd->cbits[c+cbit_word]; try_next = FALSE; break; case OP_WORDCHAR: for (c = 0; c < 32; c++) start_bits[c] |= cd->cbits[c+cbit_word]; try_next = FALSE; break; /* One or more character type fudges the pointer and restarts, knowing it will hit a single character type and stop there. */ case OP_TYPEPLUS: case OP_TYPEMINPLUS: tcode++; break; case OP_TYPEEXACT: tcode += 3; break; /* Zero or more repeats of character types set the bits and then try again. */ case OP_TYPEUPTO: case OP_TYPEMINUPTO: tcode += 2; /* Fall through */ case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEQUERY: case OP_TYPEMINQUERY: switch(tcode[1]) { case OP_ANY: return FALSE; case OP_NOT_DIGIT: for (c = 0; c < 32; c++) start_bits[c] |= ~cd->cbits[c+cbit_digit]; break; case OP_DIGIT: for (c = 0; c < 32; c++) start_bits[c] |= cd->cbits[c+cbit_digit]; break; case OP_NOT_WHITESPACE: for (c = 0; c < 32; c++) start_bits[c] |= ~cd->cbits[c+cbit_space]; break; case OP_WHITESPACE: for (c = 0; c < 32; c++) start_bits[c] |= cd->cbits[c+cbit_space]; break; case OP_NOT_WORDCHAR: for (c = 0; c < 32; c++) start_bits[c] |= ~cd->cbits[c+cbit_word]; break; case OP_WORDCHAR: for (c = 0; c < 32; c++) start_bits[c] |= cd->cbits[c+cbit_word]; break; } tcode += 2; break; /* Character class where all the information is in a bit map: set the bits and either carry on or not, according to the repeat count. If it was a negative class, and we are operating with UTF-8 characters, any byte with a value >= 0xc4 is a potentially valid starter because it starts a character with a value > 255. */ case OP_NCLASS: if (utf8) { start_bits[24] |= 0xf0; /* Bits for 0xc4 - 0xc8 */ memset(start_bits+25, 0xff, 7); /* Bits for 0xc9 - 0xff */ } /* Fall through */ case OP_CLASS: { tcode++; /* In UTF-8 mode, the bits in a bit map correspond to character values, not to byte values. However, the bit map we are constructing is for byte values. So we have to do a conversion for characters whose value is > 127. In fact, there are only two possible starting bytes for characters in the range 128 - 255. */ if (utf8) { for (c = 0; c < 16; c++) start_bits[c] |= tcode[c]; for (c = 128; c < 256; c++) { if ((tcode[c/8] & (1 << (c&7))) != 0) { int d = (c >> 6) | 0xc0; /* Set bit for this starter */ start_bits[d/8] |= (1 << (d&7)); /* and then skip on to the */ c = (c & 0xc0) + 0x40 - 1; /* next relevant character. */ } } } /* In non-UTF-8 mode, the two bit maps are completely compatible. */ else { for (c = 0; c < 32; c++) start_bits[c] |= tcode[c]; } /* Advance past the bit map, and act on what follows */ tcode += 32; switch (*tcode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRQUERY: case OP_CRMINQUERY: tcode++; break; case OP_CRRANGE: case OP_CRMINRANGE: if (((tcode[1] << 8) + tcode[2]) == 0) tcode += 5; else try_next = FALSE; break; default: try_next = FALSE; break; } } break; /* End of bitmap class handling */ } /* End of switch */ } /* End of try_next loop */ code += GET(code, 1); /* Advance to next branch */ } while (*code == OP_ALT); return TRUE; } /************************************************* * Study a compiled expression * *************************************************/ /* This function is handed a compiled expression that it must study to produce information that will speed up the matching. It returns a pcre_extra block which then gets handed back to pcre_exec(). Arguments: re points to the compiled expression options contains option bits errorptr points to where to place error messages; set NULL unless error Returns: pointer to a pcre_extra block, with study_data filled in and the appropriate flag set; NULL on error or if no optimization possible */ EXPORT pcre_extra * pcre_study(const pcre *external_re, int options, const char **errorptr) { uschar start_bits[32]; pcre_extra *extra; pcre_study_data *study; const real_pcre *re = (const real_pcre *)external_re; uschar *code = (uschar *)re + sizeof(real_pcre) + (re->name_count * re->name_entry_size); compile_data compile_block; *errorptr = NULL; if (re == NULL || re->magic_number != MAGIC_NUMBER) { *errorptr = "argument is not a compiled regular expression"; return NULL; } if ((options & ~PUBLIC_STUDY_OPTIONS) != 0) { *errorptr = "unknown or incorrect option bit(s) set"; return NULL; } /* For an anchored pattern, or an unanchored pattern that has a first char, or a multiline pattern that matches only at "line starts", no further processing at present. */ if ((re->options & (PCRE_ANCHORED|PCRE_FIRSTSET|PCRE_STARTLINE)) != 0) return NULL; /* Set the character tables in the block which is passed around */ compile_block.lcc = re->tables + lcc_offset; compile_block.fcc = re->tables + fcc_offset; compile_block.cbits = re->tables + cbits_offset; compile_block.ctypes = re->tables + ctypes_offset; /* See if we can find a fixed set of initial characters for the pattern. */ memset(start_bits, 0, 32 * sizeof(uschar)); if (!set_start_bits(code, start_bits, (re->options & PCRE_CASELESS) != 0, (re->options & PCRE_UTF8) != 0, &compile_block)) return NULL; /* Get a pcre_extra block and a pcre_study_data block. The study data is put in the latter, which is pointed to by the former, which may also get additional data set later by the calling program. At the moment, the size of pcre_study_data is fixed. We nevertheless save it in a field for returning via the pcre_fullinfo() function so that if it becomes variable in the future, we don't have to change that code. */ extra = (pcre_extra *)(pcre_malloc) (sizeof(pcre_extra) + sizeof(pcre_study_data)); if (extra == NULL) { *errorptr = "failed to get memory"; return NULL; } study = (pcre_study_data *)((char *)extra + sizeof(pcre_extra)); extra->flags = PCRE_EXTRA_STUDY_DATA; extra->study_data = study; study->size = sizeof(pcre_study_data); study->options = PCRE_STUDY_MAPPED; memcpy(study->start_bits, start_bits, sizeof(start_bits)); return extra; } /* End of study.c */ avenger-0.8.5/libasync/str.C0000644000175000017500000000473111221237220012611 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "str.h" void (*const strobj_opdel) (void *) (operator delete); void suio_print (suio *uio, const str &s) { if (s.len () <= suio::smallbufsize) uio->copy (s.cstr (), s.len ()); else { uio->print (s.cstr (), s.len ()); uio->iovcb (wrap (&s.b.Xplug, s.b.Xleak ())); } } const strbuf & strbuf_cat (const strbuf &b, const char *p, bool copy) { suio *uio = b.tosuio (); if (copy) uio->copy (p, strlen (p)); else suio_printcheck (uio, p, strlen (p)); return b; } const strbuf & operator<< (const strbuf &sb, const char *a) { return strbuf_cat (sb, a); } const strbuf operator<< (const str &s, const char *a) { return strbuf (s).cat (a); } str suio_getline (suio *uio) { if (size_t n = uio->linelen ()) { mstr m (n - 1); uio->copyout (m, n - 1); uio->rembytes (n); if (m.len () && m.cstr ()[m.len () - 1] == '\r') m.setlen (m.len () -1 ); return m; } return NULL; } strobj * str::iov2strobj (const iovec *iov, int cnt) { size_t l = iovsize (iov, cnt); strobj *b = strobj::alloc (1 + l); b->len = l; char *p = b->dat (); for (const iovec *end = iov + cnt; iov < end; iov++) { memcpy (p, iov->iov_base, iov->iov_len); p += iov->iov_len; } *p = '\0'; assert (p == b->dat () + l); return b; } strbuf::strbuf (const char *fmt, ...) : uio (New refcounted) { va_list ap; va_start (ap, fmt); suio_vuprintf (uio, fmt, ap); va_end (ap); } const strbuf & strbuf::fmt (const char *fmt, ...) const { va_list ap; va_start (ap, fmt); suio_vuprintf (uio, fmt, ap); va_end (ap); return *this; } /* For use from the debugger */ const char * cstr (const str s) { return s; } const char * cstrp (const str *s) { return *s; } avenger-0.8.5/libasync/err.h0000644000175000017500000000726511221237220012643 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_ERR_H_ #define _ASYNC_ERR_H_ 1 #include "str.h" extern bssstr progname; extern str progdir; extern void (*fatalhook) (); extern int errfd; extern bool fatal_no_destruct; extern void (*_err_output) (suio *, int); extern void (*_err_reset_hook) (); void err_reset (); void _err_output_sync (suio *, int); void setprogname (char *argv0); void setprogpid (int p); /* Old-style C functions for compatibility */ extern "C" { void sfs_warn (const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); void sfs_warnx (const char *fmt, ...) __attribute__ ((format (printf, 1, 2))); void sfs_vwarn (const char *fmt, va_list ap); void sfs_vwarnx (const char *fmt, va_list ap); void fatal (const char *fmt, ...) __attribute__ ((noreturn, format (printf, 1, 2))); void panic (const char *fmt, ...) __attribute__ ((noreturn, format (printf, 1, 2))); } class warnobj : public strbuf { const int flags; public: enum { xflag = 1, fatalflag = 2, panicflag = 4, timeflag = 8 }; explicit warnobj (int); ~warnobj (); const warnobj &operator() (const char *fmt, ...) const __attribute__ ((format (printf, 2, 3))); }; #define warn warnobj (0) #define vwarn warn.vfmt #define warnx warnobj (int (::warnobj::xflag)) #define warnt warnobj (int (::warnobj::timeflag)) #define vwarnx warnx.vfmt #ifndef __attribute__ /* Fatalobj is just a warnobj with a noreturn destructor. */ class fatalobj : public warnobj { public: explicit fatalobj (int f) : warnobj (f) {} ~fatalobj () __attribute__ ((noreturn)); }; #else /* __attribute__ */ # define fatalobj warnobj #endif /* __attribute__ */ #define fatal fatalobj (int (::warnobj::fatalflag)) #define panic fatalobj (int (::warnobj::panicflag)) ("%s\n", __BACKTRACE__) struct traceobj : public strbuf { int current_level; const char *prefix; const bool dotime; bool doprint; traceobj (int current_level, const char *prefix = "", bool dotime = false) : current_level (current_level), prefix (prefix), dotime (dotime) {} ~traceobj (); void init (); const traceobj &operator() (int threshold = 0); const traceobj &operator() (int threshold, const char *fmt, ...) __attribute__ ((format (printf, 3, 4))); }; template inline const traceobj & operator<< (const traceobj &sb, const T &a) { if (sb.doprint) strbuf_cat (sb, a); return sb; } inline const traceobj & operator<< (const traceobj &sb, const str &s) { if (sb.doprint) suio_print (sb.tosuio (), s); return sb; } #undef assert #define assert(e) \ do { \ if (!(e)) \ panic ("assertion \"%s\" failed at %s\n", #e, __FL__); \ } while (0) #ifdef DMALLOC inline void myabort () __attribute__ ((noreturn)); inline void myabort () { static bool shutdown_called; if (!shutdown_called) { shutdown_called = true; dmalloc_shutdown (); } abort (); } #else /* !DMALLOC */ # define myabort abort #endif /* !DMALLOC */ #endif /* !_ASYNC_ERR_H_ */ avenger-0.8.5/libasync/resolvconf.C0000644000175000017500000000475012260427161014173 00000000000000 #include "amisc.h" #include "parseopt.h" #include "vec.h" #include "dnsimpl.h" struct rcparser : public parseargs { explicit rcparser (str file) : parseargs (file) {} void error (str) {} }; str satostr (const sockaddr_storage *ss) { char host[NI_MAXHOST]; char port[NI_MAXSERV]; if (getnameinfo (reinterpret_cast (ss), sizeof (*ss), host, sizeof (host), port, sizeof (port), NI_NUMERICHOST|NI_NUMERICSERV)) return NULL; str res = strbuf ("[%s]:%s", host, port); return res; } bool strtosa (sockaddr_storage *ss, socklen_t *lenp, const char *p) { static addrinfo hints; if (!hints.ai_flags) hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV; str addr; const char *port; if (*p == '[') { const char *e = strchr (++p, ']'); if (!e) return false; addr.setbuf (p, e - p); port = *e == ':' ? e + 1 : "53"; } else { addr = p; port = "53"; } struct addrinfo *ai; if (getaddrinfo (addr, port, &hints, &ai)) return false; if (lenp) *lenp = ai->ai_addrlen; memcpy (ss, ai->ai_addr, ai->ai_addrlen); freeaddrinfo (ai); return true; } void show_resolv_conf (const parsed_resolv_conf &rc) { strbuf sb ("parsed resolv.conf:\n search"); for (const str *p = rc.searchlist.base(), *e = rc.searchlist.lim(); p < e; ++p) sb << " " << *p; sb << "\n"; for (const sockaddr_storage *p = rc.resolvers.base(), *e = rc.resolvers.lim(); p < e; ++p) { sb << " nameserver " << satostr (p) << "\n"; } warn << sb; } void parse_resolv_conf (parsed_resolv_conf *out, const str &path, bool v4only) { rcparser pa (path); union { sockaddr_storage ss; sockaddr_in sin; }; out->resolvers.clear (); out->resolvers_sa_len.clear (); out->searchlist.clear (); vec av; while (pa.getline (&av)) { socklen_t len; if (av[0] == "nameserver" && av.size() >= 2 && strtosa (&ss, &len, av[1]) && (ss.ss_family == AF_INET || !v4only)) { if (ss.ss_family == AF_INET && sin.sin_addr.s_addr == INADDR_ANY) sin.sin_addr.s_addr = INADDR_LOOPBACK; out->resolvers.push_back (ss); out->resolvers_sa_len.push_back (len); } else if (av[0] == "domain" || av[0] == "search") for (str *p = av.base() + 1, *e = av.lim(); p < e; p++) out->searchlist.push_back (*p); } if (out->resolvers.empty()) { bzero (&ss, sizeof (ss)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_LOOPBACK; sin.sin_port = htons (53); out->resolvers.push_back (ss); } } avenger-0.8.5/libasync/callback.h0000644000175000017500000031173411221237220013606 00000000000000#if 0 /* -*-perl-*- */ # /* # $Id$ # # This header file was automatically generated by itself. # (Yup, it's a C++ header file and a perl script.) # # Copyright (C) 1998-2004 David Mazieres (dm@uun.org) # # 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 # # Note: For the purposes of the GNU General Public License, source # includes the source to the perl script, not just the resulting # header file, callback.h. However, since the perl script is # conveniently embedded in the header file, you needn't do anything # special to distribute source as long as you don't take the perl out # of the header. # # WHAT IS THIS? # # This C++ header file defines the template class callback--a type # that approximates function currying. # # An object of type callback contains a member R operator() # (B1, B2)--Thus callbacks are function objects with the first # template type specifying the return of the function and the # remaining arguments specifying the types of the arguments to pass # the function. # # Callbacks can have any number of arguments up to $NA below. # Template arguments that aren't specified default to void and don't # need to be passed in. Thus, a callback acts like a function # with signature "int fn ()", a callback acts like a # function with signature "int fn (char *)", and so forth. # # Each callback class has two type members, ptr and ref, specyfing # refcounted pointers and references to the callback object # respectively. (See refcnt.h for an explanation of ptr and ref). # # The function wrap is used to create references to callbacks. Given # a function with signature "R fn (A1, A2, A3)", wrap can generate # the following references: # # wrap (fn) -> callback::ref # wrap (fn, a1) -> callback::ref # wrap (fn, a1, a2) -> callback::ref # wrap (fn, a1, a2, a3) -> callback::ref # # When the resulting callback is actually called, it invokes fn. The # argument list it passes fn starts with whatever arguments were # initially passed to wrap and then contains whatever arguments are # given to the callback object. For example, given fn above, this # code ends up calling "fn (a1, a2, a3)" and assigning the return # value to r; # # R r; # A1 a1; # A2 a2; # A3 a3; # callback::ptr cb; # # cb = wrap (fn, a1); # r = (*cb) (a2, a3); # # One can create callbacks from class methods as well as global # functions. To do this, simply pass the object as the first # parameter to wrap, and the method as the second. For example: # # struct foo { # void bar (int, char *); # callback::ref baz () { # return wrap (this, &foo::bar, 7); # } # }; # # Note the only way to generate pointers to class members in ANSI C++ # is with fully qualified member names. "&foo::bar" cannot be # abbreviated to "&bar" in the above example, though most C++ # compilers still accept that syntax. # # If wrap is called with a refcounted ref or ptr to a object, instead # of a simple pointer, the resulting callback will maintain a # reference to the object, ensuring it is not deleted. For example, # in the following code, baz returns a callback with a reference to # the current object. This ensures that a foo will not be deleted # until after the callback has been deleted. Without mkref, if a # callback happened after the reference count on a foo object went to # zero, the foo object would previously have been deleted and its # vtable pointer likely clobbered, resulting in a core dump. # # struct foo : public virtual refcount { # virtual void bar (int, char *); # callback::ref baz () { # return wrap (mkref (this), &foo::bar, 7); # } # }; # # An example: # # void # printstrings (char *a, char *b, char *c) # { # printf ("%s %s %s\n", a, b, c); # } # # int # main () # { # callback::ref cb1 = wrap (printstrings, "cb1a", "cb1b"); # callback::ref cb2 = wrap (printstrings, "cb2a"); # callback::ref cb3 = wrap (printstrings); # # (*cb1) ("cb1c"); // prints: cb1a cb1b cb1c # (*cb2) ("cb2b", "cb2c"); // prints: cb2a cb2b cb2c # (*cb3) ("cb3a", "cb3b", "cb3c"); // prints: cb3a cb3b cb3c # # return 0; # } eval 'exec perl -w -S $0 ${1+"$@"}' if 0; use strict; my $NA = 5; my $NB = 3; my $PARTIALSPEC = 0; # 0 May work around compiler bugs my $RETURNVOID = 1; # 0 May work around compiler bugs my $verbosedestruct = 0; my ($ia, $ib); my $enddebug = '#endif /' . '* WRAP_DEBUG *' . '/'; my $elsenotdebug = '#else /' . '* !WRAP_DEBUG *' . '/'; my $endnotdebug = '#endif /' . '* !WRAP_DEBUG *' . '/'; my $bc = '/' . '*'; my $ec = '*' . '/'; sub jc { join (', ', @_); } sub mklist ($$) { my ($pat, $n) = @_; my @res = map { my $ret = $pat; $ret =~ s/%/$_/g; $ret; } (1 .. $n); wantarray ? @res : jc (@res); } sub pcallback ($) { my $b = shift; my $tmpparam = jc ('class R', mklist ('class B%', $b)); my $tmpargs = jc ('R', mklist ('B%', $b)); my $specargs = $b == $NB ? '' : "<" . $tmpargs . ">"; my $cbargs = mklist ('B%', $b); print <<"EOF"; template<$tmpparam> class callback$specargs { public: typedef struct ref > ref; typedef struct ptr > ptr; #if WRAP_DEBUG const char *const dest; const char *const src; const char *const line; callback (const char *df, const char *f, const char *l) : dest (df[0] == '&' ? df + 1 : df), src (f), line (l) {} $enddebug virtual R operator() ($cbargs) = 0; virtual ~callback () {} }; EOF return if (!$PARTIALSPEC); my $rbparam = jc ('class R', mklist ('class B%', $b)); my $bargs = jc (mklist ('const B% &b%', $b)); my $blist = jc (mklist ('b%', $b)); print <<"EOF"; template<$rbparam> class refops > typedef callback<$tmpargs> cb_t; REFOPS_DEFAULT (cb_t); R operator() ($bargs) const { return (*p) ($blist); } }; EOF return if ($RETURNVOID); my $bparam = mklist ('class B%', $b); $tmpargs = jc ('void', mklist ('B%', $b)); print <<"EOF"; template<$bparam> class refops > typedef callback<$tmpargs> cb_t; REFOPS_DEFAULT (cb_t); void operator() ($bargs) const { (*p) ($blist); } }; EOF } sub pcallback_b_a ($$) { my ($b, $a) = @_; my $type = "callback_${b}_${a}"; my $tmpparam = jc ('class R', mklist ('class B%', $b), mklist ('class A%', $a)); my $RBlist = jc ('R', mklist ('B%', $b)); my $ABlist = jc (mklist ('A%', $a), mklist ('B%', $b)); my $adecl = join ('', mklist (" A% a%;\n", $a)); my $aargs = jc ('cb_t ff', mklist ('const A% &aa%', $a)); my $ainit = jc ('f (ff)', mklist ('a% (aa%)', $a)); my $bargs = mklist ('B% b%', $b); my $ablist = jc (mklist ('a%', $a), mklist ('b%', $b)); print <<"EOF"; template<$tmpparam> class $type : public callback<$RBlist> { typedef R (*cb_t) ($ABlist); cb_t f; ${adecl}public: $type (callback_line_param $aargs) : callback_line_init (callback<$RBlist>) $ainit {} R operator() ($bargs) { return f ($ablist); } }; EOF return if ($RETURNVOID); my $specparam = jc (mklist ('class B%', $b), mklist ('class A%', $a)); my $specargs = jc ('void', mklist ('B%', $b), mklist ('A%', $a)); $RBlist = jc ('void', mklist ('B%', $b)); print <<"EOF"; template<$specparam> class $type<$specargs> : public callback<$RBlist> { typedef void (*cb_t) ($ABlist); cb_t f; ${adecl}public: $type (callback_line_param $aargs) : callback_line_init (callback<$RBlist>) $ainit {} void operator() ($bargs) { f ($ablist); } }; EOF } sub pcallback_c_b_a ($$) { my ($b, $a) = @_; my $type = "callback_c_${b}_${a}"; my $tmpparam = jc ('class P, class C, class R', mklist ('class B%', $b), mklist ('class A%', $a)); my $RBlist = jc ('R', mklist ('B%', $b)); my $ABlist = jc (mklist ('A%', $a), mklist ('B%', $b)); my $adecl = join ('', mklist (" A% a%;\n", $a)); my $aargs = jc ('const P &cc, cb_t ff', mklist ('const A% &aa%', $a)); my $ainit = jc ('c (cc), f (ff)', mklist ('a% (aa%)', $a)); my $bargs = mklist ('B% b%', $b); my $ablist = jc (mklist ('a%', $a), mklist ('b%', $b)); print <<"EOF"; template<$tmpparam> class $type : public callback<$RBlist> { typedef R (C::*cb_t) ($ABlist); P c; cb_t f; #if WRAP_USE_NODELETE ${adecl} int deleted; public: $type (callback_line_param $aargs) : callback_line_init (callback<$RBlist>) $ainit, deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~$type () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() ($bargs) { if (deleted) panic ("callback from %s to %s on deleted object\\n", this->line, this->dest); return ((*c).*f) ($ablist); } #else $bc !WRAP_USE_NODELETE $ec ${adecl}public: $type (callback_line_param $aargs) : callback_line_init (callback<$RBlist>) $ainit {} R operator() ($bargs) { return ((*c).*f) ($ablist); } #endif $bc !WRAP_USE_NODELETE $ec }; EOF return if ($RETURNVOID); my $specparam = jc ('class P, class C', mklist ('class B%', $b), mklist ('class A%', $a)); my $specargs = jc ('P, C, void' , mklist ('B%', $b), mklist ('A%', $a)); $RBlist = jc ('void', mklist ('B%', $b)); print <<"EOF"; template<$specparam> class $type<$specargs> : public callback<$RBlist> { typedef void (C::*cb_t) ($ABlist); P c; cb_t f; ${adecl}public: $type (callback_line_param $aargs) : callback_line_init (callback<$RBlist>) $ainit {} void operator() ($bargs) { ((*c).*f) ($ablist); } }; EOF } sub pwrap_b_a ($$) { my ($b, $a) = @_; my $tmpparam = jc ('class R', mklist ('class B%', $b), mklist ('class A%, class AA%', $a)); my $rtargs = jc ('R', mklist ('B%', $b), mklist ('A%', $a)); my $rtype = "refcounted >"; my $ABlist = jc (mklist ('A%', $a), mklist ('B%', $b)); my $fargs = jc ("R (*f) ($ABlist)", mklist ('const AA% &a%', $a)); my $falist = jc ('f', mklist ('a%', $a)); print <<"EOF"; template<$tmpparam> static inline $rtype * wrap (wrap_line_param $fargs) { return wNew ($rtype) (wrap_line_arg $falist); } EOF } sub pwrap_c_b_a ($$) { my ($b, $a) = @_; my $tmpparam = jc ('class C', 'class R', mklist ('class B%', $b), mklist ('class A%, class AA%', $a)); my $rtargs = jc ('C *', 'C', 'R', mklist ('B%', $b), mklist ('A%', $a)); my $rtype = "refcounted >"; my $ABlist = jc (mklist ('A%', $a), mklist ('B%', $b)); my $fargs = jc ("C *p, R (C::*f) ($ABlist)", mklist ('const AA% &a%', $a)); my $falist = jc ('p, f', mklist ('a%', $a)); print <<"EOF"; template<$tmpparam> static inline $rtype * wrap (wrap_line_param $fargs) { return wNew ($rtype) (wrap_c_line_arg $falist); } EOF $rtargs = jc ('ref', 'C', 'R', mklist ('B%', $b), mklist ('A%', $a)); $rtype = "refcounted >"; $fargs = jc ("const ref &p, R (C::*f) ($ABlist)", mklist ('const AA% &a%', $a)); my $f2args = jc ("const ptr &p, R (C::*f) ($ABlist)", mklist ('const AA% &a%', $a)); my $f3args = jc ("const refcounted *p, R (C::*f) ($ABlist)", mklist ('const AA% &a%', $a)); $falist = jc ('p, f', mklist ('a%', $a)); print <<"EOF"; template<$tmpparam> static inline $rtype * wrap (wrap_line_param $fargs) { return wNew ($rtype) (wrap_c_line_arg $falist); } template<$tmpparam> static inline $rtype * wrap (wrap_line_param $f2args) { return wNew ($rtype) (wrap_c_line_arg $falist); } template<$tmpparam> static inline $rtype * wrap (wrap_line_param $f3args) { return wNew ($rtype) (wrap_c_line_arg $falist); } EOF } sub prefops () { return if ($PARTIALSPEC); my ($b, $opfn); $opfn = "R operator() () const { return (*p) (); }\n"; for ($b = 1; $b <= $NB; $b++) { my $tmpparam = mklist ("class BB%", $b); my $bparam = mklist ("const BB% &b%", $b); my $blist = mklist ("b%", $b); $opfn .= sprintf <<"EOF", template<$tmpparam> R operator() ($bparam) const { return (*p) ($blist); } EOF } printf <<"EOF", template<%s> class refops > { typedef callback<%s> cb_t; REFOPS_DEFAULT (cb_t); $opfn}; EOF jc ('class R', mklist ("class B%", $NB)), jc ('R', mklist ("B%", $NB)), jc ('R', mklist ("B%", $NB)); return if ($RETURNVOID); $opfn = "void operator() () { return (*p) (); }\n"; for ($b = 1; $b <= $NB; $b++) { my $tmpparam = mklist ("class BB%", $b); my $bparam = mklist ("const BB% &b%", $b); my $blist = mklist ("b%", $b); $opfn .= sprintf <<"EOF", template<$tmpparam> void operator() ($bparam) { (*p) ($blist); } EOF } printf <<"EOF", template<%s> class refops > { typedef callback<%s> cb_t; REFOPS_DEFAULT (cb_t); $opfn}; EOF scalar mklist ("class B%", $NB), jc ('void', mklist ("B%", $NB)), jc ('void', mklist ("B%", $NB)); } sub pfile () { printf "template<%s> class callback;\n", jc ('class R', mklist ('class B% = void', $NB)); my ($a, $b); for ($b = 0; $b <= $NB; $b++) { pcallback ($b); for ($a = 0; $a <= $NA; $a++) { pcallback_b_a ($b, $a); pwrap_b_a ($b, $a); pcallback_c_b_a ($b, $a); pwrap_c_b_a ($b, $a); } } prefops; } seek DATA, 0, 0; while () { print; last if m/^\#endif \/\* perl \*\/$/; } # Note: The debugging feature requires GCC varargs macros print <<'EOF'; #ifndef _CALLBACK_H_INCLUDED_ #define _CALLBACK_H_INCLUDED_ 1 #include "refcnt.h" #ifndef WRAP_DEBUG # if defined (DMALLOC) && __GNUC__ >= 2 # define WRAP_DEBUG 1 EOF print '# endif /', '* DMALLOC && gcc >= 2 *', "/\n"; print '#endif /', '* !WRAP_DEBUG *', "/\n"; print <<"EOF"; #define wNew New #if WRAP_DEBUG # define callback_line_param \\ const char *dfunc, const char *func, const char *line, # define wrap_line_param const char *wa1, const char *wa2, \\ const char *func, const char *line, # define wrap_line_arg wa1, func, line, # define wrap_c_line_arg wa2, func, line, # define callback_line_init(super...) super (dfunc, func, line), # define wrap _wrap # ifdef DMALLOC # undef wNew # define wNew new (dmalloc, line, __LINE__) # define WRAP_USE_NODELETE 1 template inline void maybe_nodelete_addptr (const ref &p, const char *fl, int *fp) { } template inline void maybe_nodelete_addptr (const ptr &p, const char *fl, int *fp) { } template inline void maybe_nodelete_addptr (C *p, const char *fl, int *fp) { nodelete_addptr (p, fl, fp); } template inline void maybe_nodelete_remptr (const ref &p, const char *fl, int *fp) { } template inline void maybe_nodelete_remptr (const ptr &p, const char *fl, int *fp) { } template inline void maybe_nodelete_remptr (C *p, const char *fl, int *fp) { nodelete_remptr (p, fl, fp); } EOF print '# endif /', '* DMALLOC *', "/\n"; print '#else /', '* !WRAP_DEBUG *', "/\n"; print <<'EOF'; # define callback_line_param # define wrap_line_param # define wrap_line_arg # define wrap_c_line_arg # define callback_line_init(super...) EOF print '#endif /', '* !WRAP_DEBUG *', "/\n\n"; pfile; print <<"EOF"; #undef callback_line_param #undef wrap_line_param #undef wrap_line_arg #undef wrap_c_line_arg #if WRAP_DEBUG # undef wrap # define wrap_arg1(arg_1, arg_rest...) #arg_1 # define wrap_arg2(arg_1, arg_rest...) wrap_arg1 (arg_rest) # define do_wrap(__func_name, __do_wrap_args...) \\ _wrap (wrap_arg1(__do_wrap_args), wrap_arg2(__do_wrap_args), \\ __func_name, __FL__, ## __do_wrap_args) # define wrap(__wrap_args...) do_wrap(__PRETTY_FUNCTION__, __wrap_args) # define gwrap(__wrap_args...) \\ (nodelete_ignore () ? do_wrap(__FL__, __wrap_args) : 0) $elsenotdebug # define gwrap wrap $endnotdebug EOF # Note that gwrap is for use outside of functions, because with some # versions of gcc, using __PRETTY_FUNCTION__ outside of any function # causes link-time errors print "\n", '#endif /', '* !_CALLBACK_H_INCLUDED_ *', '/', "\n"; __END__ # */ #endif /* perl */ #ifndef _CALLBACK_H_INCLUDED_ #define _CALLBACK_H_INCLUDED_ 1 #include "refcnt.h" #ifndef WRAP_DEBUG # if defined (DMALLOC) && __GNUC__ >= 2 # define WRAP_DEBUG 1 # endif /* DMALLOC && gcc >= 2 */ #endif /* !WRAP_DEBUG */ #define wNew New #if WRAP_DEBUG # define callback_line_param \ const char *dfunc, const char *func, const char *line, # define wrap_line_param const char *wa1, const char *wa2, \ const char *func, const char *line, # define wrap_line_arg wa1, func, line, # define wrap_c_line_arg wa2, func, line, # define callback_line_init(super...) super (dfunc, func, line), # define wrap _wrap # ifdef DMALLOC # undef wNew # define wNew new (dmalloc, line, __LINE__) # define WRAP_USE_NODELETE 1 template inline void maybe_nodelete_addptr (const ref &p, const char *fl, int *fp) { } template inline void maybe_nodelete_addptr (const ptr &p, const char *fl, int *fp) { } template inline void maybe_nodelete_addptr (C *p, const char *fl, int *fp) { nodelete_addptr (p, fl, fp); } template inline void maybe_nodelete_remptr (const ref &p, const char *fl, int *fp) { } template inline void maybe_nodelete_remptr (const ptr &p, const char *fl, int *fp) { } template inline void maybe_nodelete_remptr (C *p, const char *fl, int *fp) { nodelete_remptr (p, fl, fp); } # endif /* DMALLOC */ #else /* !WRAP_DEBUG */ # define callback_line_param # define wrap_line_param # define wrap_line_arg # define wrap_c_line_arg # define callback_line_init(super...) #endif /* !WRAP_DEBUG */ template class callback; template class callback { public: typedef struct ref > ref; typedef struct ptr > ptr; #if WRAP_DEBUG const char *const dest; const char *const src; const char *const line; callback (const char *df, const char *f, const char *l) : dest (df[0] == '&' ? df + 1 : df), src (f), line (l) {} #endif /* WRAP_DEBUG */ virtual R operator() () = 0; virtual ~callback () {} }; template class callback_0_0 : public callback { typedef R (*cb_t) (); cb_t f; public: callback_0_0 (callback_line_param cb_t ff) : callback_line_init (callback) f (ff) {} R operator() () { return f (); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) ()) { return wNew (refcounted >) (wrap_line_arg f); } template class callback_c_0_0 : public callback { typedef R (C::*cb_t) (); P c; cb_t f; #if WRAP_USE_NODELETE int deleted; public: callback_c_0_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_0_0 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() () { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (); } #else /* !WRAP_USE_NODELETE */ public: callback_c_0_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff) {} R operator() () { return ((*c).*f) (); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) ()) { return wNew (refcounted >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R> > * wrap (wrap_line_param const ref &p, R (C::*f) ()) { return wNew (refcounted, C, R> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R> > * wrap (wrap_line_param const ptr &p, R (C::*f) ()) { return wNew (refcounted, C, R> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R> > * wrap (wrap_line_param const refcounted *p, R (C::*f) ()) { return wNew (refcounted, C, R> >) (wrap_c_line_arg p, f); } template class callback_0_1 : public callback { typedef R (*cb_t) (A1); cb_t f; A1 a1; public: callback_0_1 (callback_line_param cb_t ff, const A1 &aa1) : callback_line_init (callback) f (ff), a1 (aa1) {} R operator() () { return f (a1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1), const AA1 &a1) { return wNew (refcounted >) (wrap_line_arg f, a1); } template class callback_c_0_1 : public callback { typedef R (C::*cb_t) (A1); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; int deleted; public: callback_c_0_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_0_1 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() () { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1); } #else /* !WRAP_USE_NODELETE */ A1 a1; public: callback_c_0_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1) {} R operator() () { return ((*c).*f) (a1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1), const AA1 &a1) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, A1> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1), const AA1 &a1) { return wNew (refcounted, C, R, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, A1> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1), const AA1 &a1) { return wNew (refcounted, C, R, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, A1> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1), const AA1 &a1) { return wNew (refcounted, C, R, A1> >) (wrap_c_line_arg p, f, a1); } template class callback_0_2 : public callback { typedef R (*cb_t) (A1, A2); cb_t f; A1 a1; A2 a2; public: callback_0_2 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2) {} R operator() () { return f (a1, a2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_line_arg f, a1, a2); } template class callback_c_0_2 : public callback { typedef R (C::*cb_t) (A1, A2); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; int deleted; public: callback_c_0_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_0_2 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() () { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; public: callback_c_0_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2) {} R operator() () { return ((*c).*f) (a1, a2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, A1, A2> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, A1, A2> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, A1, A2> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template class callback_0_3 : public callback { typedef R (*cb_t) (A1, A2, A3); cb_t f; A1 a1; A2 a2; A3 a3; public: callback_0_3 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() () { return f (a1, a2, a3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3); } template class callback_c_0_3 : public callback { typedef R (C::*cb_t) (A1, A2, A3); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; int deleted; public: callback_c_0_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_0_3 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() () { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; public: callback_c_0_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() () { return ((*c).*f) (a1, a2, a3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, A1, A2, A3> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, A1, A2, A3> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, A1, A2, A3> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template class callback_0_4 : public callback { typedef R (*cb_t) (A1, A2, A3, A4); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; public: callback_0_4 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() () { return f (a1, a2, a3, a4); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4); } template class callback_c_0_4 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; int deleted; public: callback_c_0_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_0_4 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() () { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; public: callback_c_0_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() () { return ((*c).*f) (a1, a2, a3, a4); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, A1, A2, A3, A4> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, A1, A2, A3, A4> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, A1, A2, A3, A4> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template class callback_0_5 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, A5); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_0_5 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() () { return f (a1, a2, a3, a4, a5); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, A5), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4, a5); } template class callback_c_0_5 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, A5); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; int deleted; public: callback_c_0_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_0_5 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() () { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, a5); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_c_0_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() () { return ((*c).*f) (a1, a2, a3, a4, a5); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, A5), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, A5), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, A5), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, A5), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template class callback { public: typedef struct ref > ref; typedef struct ptr > ptr; #if WRAP_DEBUG const char *const dest; const char *const src; const char *const line; callback (const char *df, const char *f, const char *l) : dest (df[0] == '&' ? df + 1 : df), src (f), line (l) {} #endif /* WRAP_DEBUG */ virtual R operator() (B1) = 0; virtual ~callback () {} }; template class callback_1_0 : public callback { typedef R (*cb_t) (B1); cb_t f; public: callback_1_0 (callback_line_param cb_t ff) : callback_line_init (callback) f (ff) {} R operator() (B1 b1) { return f (b1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (B1)) { return wNew (refcounted >) (wrap_line_arg f); } template class callback_c_1_0 : public callback { typedef R (C::*cb_t) (B1); P c; cb_t f; #if WRAP_USE_NODELETE int deleted; public: callback_c_1_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_1_0 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (b1); } #else /* !WRAP_USE_NODELETE */ public: callback_c_1_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff) {} R operator() (B1 b1) { return ((*c).*f) (b1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (B1)) { return wNew (refcounted >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1> > * wrap (wrap_line_param const ref &p, R (C::*f) (B1)) { return wNew (refcounted, C, R, B1> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1> > * wrap (wrap_line_param const ptr &p, R (C::*f) (B1)) { return wNew (refcounted, C, R, B1> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (B1)) { return wNew (refcounted, C, R, B1> >) (wrap_c_line_arg p, f); } template class callback_1_1 : public callback { typedef R (*cb_t) (A1, B1); cb_t f; A1 a1; public: callback_1_1 (callback_line_param cb_t ff, const A1 &aa1) : callback_line_init (callback) f (ff), a1 (aa1) {} R operator() (B1 b1) { return f (a1, b1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, B1), const AA1 &a1) { return wNew (refcounted >) (wrap_line_arg f, a1); } template class callback_c_1_1 : public callback { typedef R (C::*cb_t) (A1, B1); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; int deleted; public: callback_c_1_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_1_1 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, b1); } #else /* !WRAP_USE_NODELETE */ A1 a1; public: callback_c_1_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1) {} R operator() (B1 b1) { return ((*c).*f) (a1, b1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, B1), const AA1 &a1) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, A1> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, B1), const AA1 &a1) { return wNew (refcounted, C, R, B1, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, A1> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, B1), const AA1 &a1) { return wNew (refcounted, C, R, B1, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, A1> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, B1), const AA1 &a1) { return wNew (refcounted, C, R, B1, A1> >) (wrap_c_line_arg p, f, a1); } template class callback_1_2 : public callback { typedef R (*cb_t) (A1, A2, B1); cb_t f; A1 a1; A2 a2; public: callback_1_2 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2) {} R operator() (B1 b1) { return f (a1, a2, b1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, B1), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_line_arg f, a1, a2); } template class callback_c_1_2 : public callback { typedef R (C::*cb_t) (A1, A2, B1); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; int deleted; public: callback_c_1_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_1_2 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, b1); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; public: callback_c_1_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2) {} R operator() (B1 b1) { return ((*c).*f) (a1, a2, b1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, B1), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, A1, A2> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, B1), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, A1, A2> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, B1), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, A1, A2> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, B1), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template class callback_1_3 : public callback { typedef R (*cb_t) (A1, A2, A3, B1); cb_t f; A1 a1; A2 a2; A3 a3; public: callback_1_3 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() (B1 b1) { return f (a1, a2, a3, b1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3); } template class callback_c_1_3 : public callback { typedef R (C::*cb_t) (A1, A2, A3, B1); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; int deleted; public: callback_c_1_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_1_3 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, b1); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; public: callback_c_1_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() (B1 b1) { return ((*c).*f) (a1, a2, a3, b1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, A1, A2, A3> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, A1, A2, A3> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, A1, A2, A3> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template class callback_1_4 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, B1); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; public: callback_1_4 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() (B1 b1) { return f (a1, a2, a3, a4, b1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4); } template class callback_c_1_4 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, B1); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; int deleted; public: callback_c_1_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_1_4 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, b1); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; public: callback_c_1_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() (B1 b1) { return ((*c).*f) (a1, a2, a3, a4, b1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, A1, A2, A3, A4> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, A1, A2, A3, A4> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, A1, A2, A3, A4> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template class callback_1_5 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, A5, B1); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_1_5 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() (B1 b1) { return f (a1, a2, a3, a4, a5, b1); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, A5, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4, a5); } template class callback_c_1_5 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, A5, B1); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; int deleted; public: callback_c_1_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_1_5 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, a5, b1); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_c_1_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() (B1 b1) { return ((*c).*f) (a1, a2, a3, a4, a5, b1); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, A5, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, A5, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, A5, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, A5, B1), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template class callback { public: typedef struct ref > ref; typedef struct ptr > ptr; #if WRAP_DEBUG const char *const dest; const char *const src; const char *const line; callback (const char *df, const char *f, const char *l) : dest (df[0] == '&' ? df + 1 : df), src (f), line (l) {} #endif /* WRAP_DEBUG */ virtual R operator() (B1, B2) = 0; virtual ~callback () {} }; template class callback_2_0 : public callback { typedef R (*cb_t) (B1, B2); cb_t f; public: callback_2_0 (callback_line_param cb_t ff) : callback_line_init (callback) f (ff) {} R operator() (B1 b1, B2 b2) { return f (b1, b2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (B1, B2)) { return wNew (refcounted >) (wrap_line_arg f); } template class callback_c_2_0 : public callback { typedef R (C::*cb_t) (B1, B2); P c; cb_t f; #if WRAP_USE_NODELETE int deleted; public: callback_c_2_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_2_0 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (b1, b2); } #else /* !WRAP_USE_NODELETE */ public: callback_c_2_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff) {} R operator() (B1 b1, B2 b2) { return ((*c).*f) (b1, b2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (B1, B2)) { return wNew (refcounted >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1, B2> > * wrap (wrap_line_param const ref &p, R (C::*f) (B1, B2)) { return wNew (refcounted, C, R, B1, B2> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1, B2> > * wrap (wrap_line_param const ptr &p, R (C::*f) (B1, B2)) { return wNew (refcounted, C, R, B1, B2> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1, B2> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (B1, B2)) { return wNew (refcounted, C, R, B1, B2> >) (wrap_c_line_arg p, f); } template class callback_2_1 : public callback { typedef R (*cb_t) (A1, B1, B2); cb_t f; A1 a1; public: callback_2_1 (callback_line_param cb_t ff, const A1 &aa1) : callback_line_init (callback) f (ff), a1 (aa1) {} R operator() (B1 b1, B2 b2) { return f (a1, b1, b2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, B1, B2), const AA1 &a1) { return wNew (refcounted >) (wrap_line_arg f, a1); } template class callback_c_2_1 : public callback { typedef R (C::*cb_t) (A1, B1, B2); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; int deleted; public: callback_c_2_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_2_1 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, b1, b2); } #else /* !WRAP_USE_NODELETE */ A1 a1; public: callback_c_2_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1) {} R operator() (B1 b1, B2 b2) { return ((*c).*f) (a1, b1, b2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, B1, B2), const AA1 &a1) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, B2, A1> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, B1, B2), const AA1 &a1) { return wNew (refcounted, C, R, B1, B2, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, B2, A1> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, B1, B2), const AA1 &a1) { return wNew (refcounted, C, R, B1, B2, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, B2, A1> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, B1, B2), const AA1 &a1) { return wNew (refcounted, C, R, B1, B2, A1> >) (wrap_c_line_arg p, f, a1); } template class callback_2_2 : public callback { typedef R (*cb_t) (A1, A2, B1, B2); cb_t f; A1 a1; A2 a2; public: callback_2_2 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2) {} R operator() (B1 b1, B2 b2) { return f (a1, a2, b1, b2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, B1, B2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_line_arg f, a1, a2); } template class callback_c_2_2 : public callback { typedef R (C::*cb_t) (A1, A2, B1, B2); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; int deleted; public: callback_c_2_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_2_2 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, b1, b2); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; public: callback_c_2_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2) {} R operator() (B1 b1, B2 b2) { return ((*c).*f) (a1, a2, b1, b2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, B1, B2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, B2, A1, A2> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, B1, B2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, B2, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, B2, A1, A2> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, B1, B2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, B2, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, B2, A1, A2> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, B1, B2), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, B2, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template class callback_2_3 : public callback { typedef R (*cb_t) (A1, A2, A3, B1, B2); cb_t f; A1 a1; A2 a2; A3 a3; public: callback_2_3 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() (B1 b1, B2 b2) { return f (a1, a2, a3, b1, b2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3); } template class callback_c_2_3 : public callback { typedef R (C::*cb_t) (A1, A2, A3, B1, B2); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; int deleted; public: callback_c_2_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_2_3 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, b1, b2); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; public: callback_c_2_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() (B1 b1, B2 b2) { return ((*c).*f) (a1, a2, a3, b1, b2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, B2, A1, A2, A3> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, B2, A1, A2, A3> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, B2, A1, A2, A3> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template class callback_2_4 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, B1, B2); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; public: callback_2_4 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() (B1 b1, B2 b2) { return f (a1, a2, a3, a4, b1, b2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4); } template class callback_c_2_4 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, B1, B2); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; int deleted; public: callback_c_2_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_2_4 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, b1, b2); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; public: callback_c_2_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() (B1 b1, B2 b2) { return ((*c).*f) (a1, a2, a3, a4, b1, b2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, B2, A1, A2, A3, A4> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, B2, A1, A2, A3, A4> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, B2, A1, A2, A3, A4> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template class callback_2_5 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, A5, B1, B2); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_2_5 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() (B1 b1, B2 b2) { return f (a1, a2, a3, a4, a5, b1, b2); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, A5, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4, a5); } template class callback_c_2_5 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, A5, B1, B2); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; int deleted; public: callback_c_2_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_2_5 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, a5, b1, b2); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_c_2_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() (B1 b1, B2 b2) { return ((*c).*f) (a1, a2, a3, a4, a5, b1, b2); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, B2, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, B2, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, B2, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, B2, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template class callback { public: typedef struct ref > ref; typedef struct ptr > ptr; #if WRAP_DEBUG const char *const dest; const char *const src; const char *const line; callback (const char *df, const char *f, const char *l) : dest (df[0] == '&' ? df + 1 : df), src (f), line (l) {} #endif /* WRAP_DEBUG */ virtual R operator() (B1, B2, B3) = 0; virtual ~callback () {} }; template class callback_3_0 : public callback { typedef R (*cb_t) (B1, B2, B3); cb_t f; public: callback_3_0 (callback_line_param cb_t ff) : callback_line_init (callback) f (ff) {} R operator() (B1 b1, B2 b2, B3 b3) { return f (b1, b2, b3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (B1, B2, B3)) { return wNew (refcounted >) (wrap_line_arg f); } template class callback_c_3_0 : public callback { typedef R (C::*cb_t) (B1, B2, B3); P c; cb_t f; #if WRAP_USE_NODELETE int deleted; public: callback_c_3_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_3_0 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2, B3 b3) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (b1, b2, b3); } #else /* !WRAP_USE_NODELETE */ public: callback_c_3_0 (callback_line_param const P &cc, cb_t ff) : callback_line_init (callback) c (cc), f (ff) {} R operator() (B1 b1, B2 b2, B3 b3) { return ((*c).*f) (b1, b2, b3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (B1, B2, B3)) { return wNew (refcounted >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1, B2, B3> > * wrap (wrap_line_param const ref &p, R (C::*f) (B1, B2, B3)) { return wNew (refcounted, C, R, B1, B2, B3> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1, B2, B3> > * wrap (wrap_line_param const ptr &p, R (C::*f) (B1, B2, B3)) { return wNew (refcounted, C, R, B1, B2, B3> >) (wrap_c_line_arg p, f); } template static inline refcounted, C, R, B1, B2, B3> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (B1, B2, B3)) { return wNew (refcounted, C, R, B1, B2, B3> >) (wrap_c_line_arg p, f); } template class callback_3_1 : public callback { typedef R (*cb_t) (A1, B1, B2, B3); cb_t f; A1 a1; public: callback_3_1 (callback_line_param cb_t ff, const A1 &aa1) : callback_line_init (callback) f (ff), a1 (aa1) {} R operator() (B1 b1, B2 b2, B3 b3) { return f (a1, b1, b2, b3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, B1, B2, B3), const AA1 &a1) { return wNew (refcounted >) (wrap_line_arg f, a1); } template class callback_c_3_1 : public callback { typedef R (C::*cb_t) (A1, B1, B2, B3); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; int deleted; public: callback_c_3_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_3_1 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2, B3 b3) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, b1, b2, b3); } #else /* !WRAP_USE_NODELETE */ A1 a1; public: callback_c_3_1 (callback_line_param const P &cc, cb_t ff, const A1 &aa1) : callback_line_init (callback) c (cc), f (ff), a1 (aa1) {} R operator() (B1 b1, B2 b2, B3 b3) { return ((*c).*f) (a1, b1, b2, b3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, B1, B2, B3), const AA1 &a1) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, B2, B3, A1> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, B1, B2, B3), const AA1 &a1) { return wNew (refcounted, C, R, B1, B2, B3, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, B2, B3, A1> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, B1, B2, B3), const AA1 &a1) { return wNew (refcounted, C, R, B1, B2, B3, A1> >) (wrap_c_line_arg p, f, a1); } template static inline refcounted, C, R, B1, B2, B3, A1> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, B1, B2, B3), const AA1 &a1) { return wNew (refcounted, C, R, B1, B2, B3, A1> >) (wrap_c_line_arg p, f, a1); } template class callback_3_2 : public callback { typedef R (*cb_t) (A1, A2, B1, B2, B3); cb_t f; A1 a1; A2 a2; public: callback_3_2 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2) {} R operator() (B1 b1, B2 b2, B3 b3) { return f (a1, a2, b1, b2, b3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, B1, B2, B3), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_line_arg f, a1, a2); } template class callback_c_3_2 : public callback { typedef R (C::*cb_t) (A1, A2, B1, B2, B3); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; int deleted; public: callback_c_3_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_3_2 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2, B3 b3) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, b1, b2, b3); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; public: callback_c_3_2 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2) {} R operator() (B1 b1, B2 b2, B3 b3) { return ((*c).*f) (a1, a2, b1, b2, b3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, B1, B2, B3), const AA1 &a1, const AA2 &a2) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, B2, B3, A1, A2> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, B1, B2, B3), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, B2, B3, A1, A2> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, B1, B2, B3), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template static inline refcounted, C, R, B1, B2, B3, A1, A2> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, B1, B2, B3), const AA1 &a1, const AA2 &a2) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2> >) (wrap_c_line_arg p, f, a1, a2); } template class callback_3_3 : public callback { typedef R (*cb_t) (A1, A2, A3, B1, B2, B3); cb_t f; A1 a1; A2 a2; A3 a3; public: callback_3_3 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() (B1 b1, B2 b2, B3 b3) { return f (a1, a2, a3, b1, b2, b3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3); } template class callback_c_3_3 : public callback { typedef R (C::*cb_t) (A1, A2, A3, B1, B2, B3); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; int deleted; public: callback_c_3_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_3_3 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2, B3 b3) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, b1, b2, b3); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; public: callback_c_3_3 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3) {} R operator() (B1 b1, B2 b2, B3 b3) { return ((*c).*f) (a1, a2, a3, b1, b2, b3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3> >) (wrap_c_line_arg p, f, a1, a2, a3); } template class callback_3_4 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, B1, B2, B3); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; public: callback_3_4 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() (B1 b1, B2 b2, B3 b3) { return f (a1, a2, a3, a4, b1, b2, b3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4); } template class callback_c_3_4 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, B1, B2, B3); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; int deleted; public: callback_c_3_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_3_4 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2, B3 b3) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, b1, b2, b3); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; public: callback_c_3_4 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4) {} R operator() (B1 b1, B2 b2, B3 b3) { return ((*c).*f) (a1, a2, a3, a4, b1, b2, b3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3, A4> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3, A4> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3, A4> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3, A4> >) (wrap_c_line_arg p, f, a1, a2, a3, a4); } template class callback_3_5 : public callback { typedef R (*cb_t) (A1, A2, A3, A4, A5, B1, B2, B3); cb_t f; A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_3_5 (callback_line_param cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() (B1 b1, B2 b2, B3 b3) { return f (a1, a2, a3, a4, a5, b1, b2, b3); } }; template static inline refcounted > * wrap (wrap_line_param R (*f) (A1, A2, A3, A4, A5, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_line_arg f, a1, a2, a3, a4, a5); } template class callback_c_3_5 : public callback { typedef R (C::*cb_t) (A1, A2, A3, A4, A5, B1, B2, B3); P c; cb_t f; #if WRAP_USE_NODELETE A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; int deleted; public: callback_c_3_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5), deleted (false) { maybe_nodelete_addptr (c, this->line, &deleted); } ~callback_c_3_5 () { maybe_nodelete_remptr (c, this->line, &deleted); } R operator() (B1 b1, B2 b2, B3 b3) { if (deleted) panic ("callback from %s to %s on deleted object\n", this->line, this->dest); return ((*c).*f) (a1, a2, a3, a4, a5, b1, b2, b3); } #else /* !WRAP_USE_NODELETE */ A1 a1; A2 a2; A3 a3; A4 a4; A5 a5; public: callback_c_3_5 (callback_line_param const P &cc, cb_t ff, const A1 &aa1, const A2 &aa2, const A3 &aa3, const A4 &aa4, const A5 &aa5) : callback_line_init (callback) c (cc), f (ff), a1 (aa1), a2 (aa2), a3 (aa3), a4 (aa4), a5 (aa5) {} R operator() (B1 b1, B2 b2, B3 b3) { return ((*c).*f) (a1, a2, a3, a4, a5, b1, b2, b3); } #endif /* !WRAP_USE_NODELETE */ }; template static inline refcounted > * wrap (wrap_line_param C *p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ref &p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const ptr &p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template static inline refcounted, C, R, B1, B2, B3, A1, A2, A3, A4, A5> > * wrap (wrap_line_param const refcounted *p, R (C::*f) (A1, A2, A3, A4, A5, B1, B2, B3), const AA1 &a1, const AA2 &a2, const AA3 &a3, const AA4 &a4, const AA5 &a5) { return wNew (refcounted, C, R, B1, B2, B3, A1, A2, A3, A4, A5> >) (wrap_c_line_arg p, f, a1, a2, a3, a4, a5); } template class refops > { typedef callback cb_t; REFOPS_DEFAULT (cb_t); R operator() () const { return (*p) (); } template R operator() (const BB1 &b1) const { return (*p) (b1); } template R operator() (const BB1 &b1, const BB2 &b2) const { return (*p) (b1, b2); } template R operator() (const BB1 &b1, const BB2 &b2, const BB3 &b3) const { return (*p) (b1, b2, b3); } }; #undef callback_line_param #undef wrap_line_param #undef wrap_line_arg #undef wrap_c_line_arg #if WRAP_DEBUG # undef wrap # define wrap_arg1(arg_1, arg_rest...) #arg_1 # define wrap_arg2(arg_1, arg_rest...) wrap_arg1 (arg_rest) # define do_wrap(__func_name, __do_wrap_args...) \ _wrap (wrap_arg1(__do_wrap_args), wrap_arg2(__do_wrap_args), \ __func_name, __FL__, ## __do_wrap_args) # define wrap(__wrap_args...) do_wrap(__PRETTY_FUNCTION__, __wrap_args) # define gwrap(__wrap_args...) \ (nodelete_ignore () ? do_wrap(__FL__, __wrap_args) : 0) #else /* !WRAP_DEBUG */ # define gwrap wrap #endif /* !WRAP_DEBUG */ #endif /* !_CALLBACK_H_INCLUDED_ */ avenger-0.8.5/libasync/malloc.C0000644000175000017500000001574513357041475013300 00000000000000/* $Id$ */ #include "amisc.h" #ifdef PYMALLOC # ifdef _POSIX_C_SOURCE # undef _POSIX_C_SOURCE # endif # include #endif /* PYMALLOC */ #ifdef DMALLOC bool dmalloc_init::initialized; void dmalloc_init::init () { if (suidsafe () < 0 && (getenv ("DMALLOC_OPTIONS") || getenv ("STKTRACE"))) { setgid (getgid ()); setuid (getuid ()); const char msg[] = "setuid disabled for malloc debugging\n"; write (2, msg, sizeof (msg) - 1); } initialized = true; } #endif /* DMALLOC */ /* The xmalloc handler will have no effect when dmalloc is used, but * we leave it in for compatibility. */ static void default_xmalloc_handler (int size) { const char msg[] = "malloc failed\n"; use (write (errfd, msg, sizeof (msg) - 1)); myabort (); } void (*xmalloc_handler) (int) = default_xmalloc_handler; #ifdef DMALLOC #undef new dmalloc_t dmalloc; #ifndef CHECK_ARRAY_DELETE # define CHECK_ARRAY_DELETE 1 #endif /* !CHECK_ARRAY_DELETE */ #if CHECK_ARRAY_DELETE /* Want to catch array new followed by non-array delete */ enum { new_array_shift = 8 }; static u_char array_marker[new_array_shift] = { 0x79, 0x46, 0x55, 0x93, 0x12, 0x69, 0xaa, 0x7f }; #endif /* !CHECK_ARRAY_DELETE */ void * operator new (size_t size, dmalloc_t, const char *file, int line) { /* As per the C++ standard, allocating 0 bytes must not return NULL, * and must return a different pointer each time... */ if (!size) size = 1; return _xmalloc_leap (file, line, size); } void * operator new[] (size_t size, dmalloc_t, const char *file, int line) { #if CHECK_ARRAY_DELETE size = size + new_array_shift; #endif /* CHECK_ARRAY_DELETE */ if (!size) size = 1; #if CHECK_ARRAY_DELETE char *ret = static_cast (_xmalloc_leap (file, line, size)); memcpy (ret, array_marker, new_array_shift); return ret + new_array_shift; #else /* !CHECK_ARRAY_DELETE */ return _xmalloc_leap (file, line, size); #endif /* !CHECK_ARRAY_DELETE */ } void * operator new (size_t size, nothrow_t, const char *file, int line) throw () { if (!size) size = 1; return _malloc_leap (file, line, size); } void * operator new[] (size_t size, nothrow_t, const char *file, int line) throw () { #if CHECK_ARRAY_DELETE size = size + new_array_shift; #endif /* CHECK_ARRAY_DELETE */ if (!size) size = 1; #if CHECK_ARRAY_DELETE char *ret = static_cast (_xmalloc_leap (file, line, size)); memcpy (ret, array_marker, new_array_shift); return ret + new_array_shift; #else /* !CHECK_ARRAY_DELETE */ return _xmalloc_leap (file, line, size); #endif /* !CHECK_ARRAY_DELETE */ } #else /* !DMALLOC */ void * xmalloc (size_t size) { void *p; #ifdef PYMALLOC if (!(p = PyMem_Malloc (size))) #else /* ! PYMALLOC */ if (!(p = malloc (size))) #endif /* PYMALLOC */ default_xmalloc_handler (size); return p; } void * xrealloc (void *o, size_t size) { void *p; #ifdef PYMALLOC if (!(p = PyMem_Realloc (o, size))) #else /* ! PYMALLOC */ if (!(p = realloc (o, size))) #endif /* PYMALLOC */ default_xmalloc_handler (size); return p; } char * xstrdup (const char *s) { char *d; d = (char *) xmalloc (strlen (s) + 1); strcpy (d, s); return d; } #endif /* !DMALLOC */ using std::bad_alloc; using std::nothrow_t; void * operator new (size_t size) { if (!size) size = 1; return txmalloc (size); } void * operator new (size_t size, nothrow_t) throw () { if (!size) size = 1; #if PYMALLOC return PyMem_Malloc (size); #else /* !PYMALLOC */ return malloc (size); #endif } #ifndef delete_throw # define delete_throw throw() #endif /* !delete_throw */ #ifndef DMALLOC void operator delete (void *ptr) delete_throw { xfree (ptr); } void * operator new[] (size_t size) { if (!size) size = 1; return txmalloc (size); } void * operator new[] (size_t size, nothrow_t) throw () { if (!size) size = 1; #if PYMALLOC return PyMem_Malloc (size); #else /* !PYMALLOC */ return malloc (size); #endif } void operator delete[] (void *ptr) delete_throw { xfree (ptr); } #else /* DMALLOC */ #include struct hashptr { hashptr () {} hash_t operator() (const void *obj) const { return reinterpret_cast (obj); } }; struct objref { const void *obj; const char *refline; int *const flagp; ihash_entry hlink; objref (const void *o, const char *fl, int *fp); ~objref (); }; static ihash objreftab; inline objref::objref (const void *o, const char *fl, int *fp) : obj (o), refline (fl), flagp (fp) { objreftab.insert (this); } inline objref::~objref () { objreftab.remove (this); } int nodelete_ignore_count; static int do_nodelete_flag; inline bool do_nodelete () { return do_nodelete_flag > 0 && !nodelete_ignore_count && !globaldestruction && objreftab.constructed (); } void nodelete_addptr (const void *obj, const char *fl, int *fp) { if (!do_nodelete_flag) { u_long dmalloc_flags = dmalloc_debug_current (); do_nodelete_flag = (dmalloc_flags && 0x800) ? 1 : -1; } if (do_nodelete ()) vNew objref (obj, fl, fp); } void nodelete_remptr (const void *obj, const char *fl, int *fp) { if (do_nodelete ()) for (objref *oref = objreftab[obj]; oref; oref = objreftab.nextkeq (oref)) if (oref->refline == fl && oref->flagp == fp) { delete oref; return; } } inline void nodelete_check (const void *ptr) { if (do_nodelete ()) for (objref *oref = objreftab[ptr]; oref; oref = objreftab.nextkeq (oref)) { if (oref->flagp) (*oref->flagp)++; else panic ("deleting ptr %p still referenced from %s\n", ptr, oref->refline); } } void operator delete (void *ptr) delete_throw { nodelete_check (ptr); if (stktrace_record > 0) dmalloc_free (__backtrace (__FILE__, 2), __LINE__, ptr, DMALLOC_FUNC_FREE); else xfree (ptr); } void * operator new[] (size_t size) { #if CHECK_ARRAY_DELETE size = size + new_array_shift; #endif /* CHECK_ARRAY_DELETE */ if (!size) size = 1; #if CHECK_ARRAY_DELETE char *ret = static_cast (txmalloc (size)); memcpy (ret, array_marker, new_array_shift); return ret + new_array_shift; #else /* !CHECK_ARRAY_DELETE */ return txmalloc (size); #endif /* !CHECK_ARRAY_DELETE */ } void * operator new[] (size_t size, nothrow_t) throw () { #if CHECK_ARRAY_DELETE size = size + new_array_shift; #endif /* CHECK_ARRAY_DELETE */ if (!size) size = 1; #if CHECK_ARRAY_DELETE char *ret = static_cast (txmalloc (size)); memcpy (ret, array_marker, new_array_shift); return ret + new_array_shift; #else /* !CHECK_ARRAY_DELETE */ return txmalloc (size); #endif /* !CHECK_ARRAY_DELETE */ } void operator delete[] (void *_ptr) delete_throw { #if CHECK_ARRAY_DELETE char *ptr = static_cast (_ptr) - new_array_shift; if (memcmp (ptr, array_marker, new_array_shift)) { char msg[] = "non-array delete of array (or fencepost error)\n"; write (errfd, msg, sizeof (msg) - 1); } xfree (ptr); #else /* !CHECK_ARRAY_DELETE */ xfree (_ptr); #endif /* !CHECK_ARRAY_DELETE */ } #endif /* DMALLOC */ avenger-0.8.5/libasync/getopt_long.h0000644000175000017500000000147511221235216014374 00000000000000/* $Id$ */ /* * Declarations for getopt_long. These are from both OpenBSD and * Linux manual pages. I believe the interface is not * copyrighted/copyrightable. The header should be compatible with * either implementation. */ #ifndef _GETOPT_LONG_H_ #define _GETOPT_LONG_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ enum { no_argument = 0, required_argument = 1, optional_argument = 2, }; struct option { const char *name; int has_arg; int *flag; int val; }; int getopt_long (int argc, char *const *argv, const char *optstring, const struct option *longopts, int *longindex); int getopt_long_only (int argc, char *const *argv, const char *optstring, const struct option *longopts, int *longindex); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !_GETOPT_LONG_H_ */ avenger-0.8.5/libasync/socket.C0000644000175000017500000002121413357041744013304 00000000000000/* $Id: socket.C,v 1.28 2009/05/11 22:09:50 dm Exp $ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #if __linux /* Needed for struct ucred */ # define _GNU_SOURCE 1 #endif /* __linux */ #include "amisc.h" #include "init.h" extern "C" { #ifdef HAVE_BINDRESVPORT # ifdef HAVE_RPC_RPC_H # include # endif /* HAVE_RPC_RPC_H */ # ifdef NEED_BINDRESVPORT_DECL int bindresvport (int, struct sockaddr_in *); # endif /* NEED_BINDRESVPORT_DECL */ #endif /* HAVE_BINDRESVPORT */ #include #include #include } #ifdef SFS_ALLOW_LARGE_BUFFER enum { maxsobufsize = 0x11000 }; /* 64K + header */ #else /* !SFS_ALLOW_LARGE_BUFFER */ enum { maxsobufsize = 0x05000 }; /* 16K + header */ #endif /* !SFS_ALLOW_LARGE_BUFFER */ int sndbufsize = maxsobufsize; int rcvbufsize = maxsobufsize; in_addr inet_bindaddr; INITFN(init_env); static void init_env () { if (char *p = safegetenv ("SNDBUFSIZE")) sndbufsize = atoi (p); if (char *p = safegetenv ("RCVBUFSIZE")) rcvbufsize = atoi (p); char *p = safegetenv ("BINDADDR"); if (!p || inet_aton (p, &inet_bindaddr) <= 0) inet_bindaddr.s_addr = htonl (INADDR_ANY); } u_int16_t inetsocket_lastport; int inetsocket_resvport (int type, u_int32_t addr) { #ifndef NORESVPORTS int s; struct sockaddr_in sin; bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (0); if (addr == INADDR_ANY) sin.sin_addr = inet_bindaddr; else sin.sin_addr.s_addr = htonl (addr); if ((s = socket (AF_INET, type, 0)) < 0) return (-1); /* Don't bother if we aren't root */ if (geteuid ()) { again0: if (bind (s, (struct sockaddr *) &sin, sizeof (sin)) >= 0) return s; if (errno == EADDRNOTAVAIL && sin.sin_addr.s_addr != htonl (addr)) { sin.sin_addr.s_addr = htonl (addr); goto again0; } close (s); return -1; } #ifdef HAVE_BINDRESVPORT again1: if (bindresvport (s, &sin) >= 0) { inetsocket_lastport = ntohs (sin.sin_port); return s; } if (errno == EADDRNOTAVAIL && sin.sin_addr.s_addr != htonl (addr)) { sin.sin_addr.s_addr = htonl (addr); goto again1; } #else /* !HAVE_BINDRESVPORT */ for (inetsocket_lastport = IPPORT_RESERVED - 1; inetsocket_lastport > IPPORT_RESERVED/2; inetsocket_lastport--) { again2: sin.sin_port = htons (inetsocket_lastport); if (bind (s, (struct sockaddr *) &sin, sizeof (sin)) >= 0) return (s); if (errno == EADDRNOTAVAIL && sin.sin_addr.s_addr != htonl (addr)) { sin.sin_addr.s_addr = htonl (addr); goto again2; } if (errno != EADDRINUSE) break; } #endif /* !HAVE_BINDRESVPORT */ close (s); return -1; #else /* NORESVPORTS */ return inetsocket (type, addr, 0); #endif /* NORESVPORTS */ } int inetsocket (int type, u_int16_t port, u_int32_t addr) { int s; int n; socklen_t sn; struct sockaddr_in sin; bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (port); if (addr == INADDR_ANY) sin.sin_addr = inet_bindaddr; else sin.sin_addr.s_addr = htonl (addr); if ((s = socket (AF_INET, type, 0)) < 0) return -1; sn = sizeof (n); n = 1; /* Avoid those annoying TIME_WAITs for TCP */ if (port && type == SOCK_STREAM && setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (char *) &n, sn) < 0) fatal ("inetsocket: SO_REUSEADDR: %s\n", strerror (errno)); #ifdef IP_FREEBIND n = 1; setsockopt (s, IPPROTO_IP, IP_FREEBIND, &n, sizeof (n)); #endif /* IP_FREEBIND */ again: if (bind (s, (struct sockaddr *) &sin, sizeof (sin)) >= 0) { #if 0 if (type == SOCK_STREAM) warn ("TCP (fd %d) bound: %s\n", s, __backtrace (__FL__)); #endif return s; } if (errno == EADDRNOTAVAIL && sin.sin_addr.s_addr != htonl (addr)) { sin.sin_addr.s_addr = htonl (addr); goto again; } close (s); return -1; } int unixsocket (const char *path) { sockaddr_un sun; if (strlen (path) >= sizeof (sun.sun_path)) { #ifdef ENAMETOOLONG errno = ENAMETOOLONG; #else /* !ENAMETOOLONG */ errno = E2BIG; #endif /* !ENAMETOOLONG */ return -1; } bzero (&sun, sizeof (sun)); sun.sun_family = AF_UNIX; strcpy (sun.sun_path, path); int fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) return -1; if (bind (fd, (sockaddr *) &sun, sizeof (sun)) < 0) { close (fd); return -1; } return fd; } int unixsocket_connect (const char *path) { sockaddr_un sun; if (strlen (path) >= sizeof (sun.sun_path)) { #ifdef ENAMETOOLONG errno = ENAMETOOLONG; #else /* !ENAMETOOLONG */ errno = E2BIG; #endif /* !ENAMETOOLONG */ return -1; } bzero (&sun, sizeof (sun)); sun.sun_family = AF_UNIX; strcpy (sun.sun_path, path); int fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) return -1; if (connect (fd, (sockaddr *) &sun, sizeof (sun)) < 0) { close (fd); return -1; } return fd; } bool isunixsocket (int fd) { sockaddr_un sun; socklen_t sunlen = sizeof (sun); bzero (&sun, sizeof (sun)); sun.sun_family = AF_UNIX; if (getsockname (fd, (sockaddr *) &sun, &sunlen) < 0 || sun.sun_family != AF_UNIX) return false; return true; } void close_on_exec (int s, bool set) { if (fcntl (s, F_SETFD, int (set)) < 0) fatal ("F_SETFD: %s\n", strerror (errno)); } int _make_async (int s) { int n; if ((n = fcntl (s, F_GETFL)) < 0 || fcntl (s, F_SETFL, n | O_NONBLOCK) < 0) return -1; return 0; } void make_async (int s) { int n; int type; socklen_t sn; if (_make_async (s) < 0) fatal ("O_NONBLOCK: %s\n", strerror (errno)); type = 0; sn = sizeof (type); if (getsockopt (s, SOL_SOCKET, SO_TYPE, (char *)&type, &sn) < 0) return; #if defined (SO_RCVBUF) && defined (SO_SNDBUF) if (type == SOCK_STREAM) n = rcvbufsize; else n = maxsobufsize; if (setsockopt (s, SOL_SOCKET, SO_RCVBUF, (char *) &n, sizeof (n)) < 0) warn ("SO_RCVBUF: %s\n", strerror (errno)); if (type == SOCK_STREAM) n = sndbufsize; else n = maxsobufsize; if (setsockopt (s, SOL_SOCKET, SO_SNDBUF, (char *) &n, sizeof (n)) < 0) warn ("SO_SNDBUF: %s\n", strerror (errno)); #endif /* SO_RCVBUF && SO_SNDBUF */ /* Enable keepalives to avoid buffering write data for infinite time */ n = 1; if (type == SOCK_STREAM && setsockopt (s, SOL_SOCKET, SO_KEEPALIVE, (char *) &n, sizeof (n)) < 0) warn ("SO_KEEPALIVE: %s\n", strerror (errno)); } void make_sync (int s) { int n; if ((n = fcntl (s, F_GETFL)) >= 0) fcntl (s, F_SETFL, n & ~O_NONBLOCK); } void tcp_nodelay (int s) { #if defined (TCP_NODELAY) || defined (IPTOS_LOWDELAY) int n = 1; #endif /* TCP_NODELAY || IPTOS_LOWDELAY */ #ifdef TCP_NODELAY if (setsockopt (s, IPPROTO_TCP, TCP_NODELAY, (char *) &n, sizeof (n)) < 0) warn ("TCP_NODELAY: %m\n"); #endif /* TCP_NODELAY */ #ifdef IPTOS_LOWDELAY setsockopt (s, IPPROTO_IP, IP_TOS, (char *) &n, sizeof (n)); #endif /* IPTOS_LOWDELAY */ } void tcp_abort (int fd) { struct linger l; l.l_onoff = 1; l.l_linger = 0; setsockopt (fd, SOL_SOCKET, SO_LINGER, (char *) &l, sizeof (l)); close (fd); } bool addreq (const sockaddr *a, const sockaddr *b, socklen_t size) { if (a->sa_family != b->sa_family) return false; switch (a->sa_family) { case AF_INET: if (implicit_cast (size) >= sizeof (sockaddr_in)) { const sockaddr_in *aa = reinterpret_cast (a); const sockaddr_in *bb = reinterpret_cast (b); return (aa->sin_addr.s_addr == bb->sin_addr.s_addr && aa->sin_port == bb->sin_port); } warn ("addreq: %d bytes is too small for AF_INET sockaddrs\n", size); return false; default: warn ("addreq: bad sa_family %d\n", a->sa_family); return false; } } #if NEED_GETPEEREID int getpeereid (int fd, uid_t *u, gid_t *g) { struct ucred cred; socklen_t credlen = sizeof (cred); int r = getsockopt (fd, SOL_SOCKET, SO_PEERCRED, &cred, &credlen); if (r >= 0) { if (u) *u = cred.uid; if (g) *g = cred.gid; } return r; } #endif /* !NEED_GETPEEREID */ avenger-0.8.5/libasync/itree.C0000644000175000017500000001644011633211145013116 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "itree.h" #define oc __opaquecontainer_pointer #define itree_entry __itree_entry_private /* Define some gross macros to avoid a lot of typing. These asssume a * local variable 'os' contains the offset of the itree_entry * structure in the opaque container structure. */ static inline struct itree_entry *oc2rb (oc, const int) __attribute__ ((const)); static inline struct itree_entry * oc2rb (oc o, const int os) { return (struct itree_entry *) ((char *) o + os); } #define up(n) oc2rb (n, os)->rbe_up #define left(n) oc2rb (n, os)->rbe_left #define right(n) oc2rb (n, os)->rbe_right #define color(n) ((n) ? oc2rb (n, os)->rbe_color : BLACK) #define lcolor(n) oc2rb (n, os)->rbe_color static void itree_left_rotate (oc *r, oc x, const int os) { oc y = right (x); if ((right (x) = left (y))) up (left (y)) = x; up (y) = up (x); if (!up (x)) *r = y; else if (x == left (up (x))) left (up (x)) = y; else right (up (x)) = y; left (y) = x; up (x) = y; } static void itree_right_rotate (oc *r, oc y, const int os) { oc x = left (y); if ((left (y) = right (x))) up (right (x)) = y; up (x) = up (y); if (!up (y)) *r = x; else if (y == right (up (y))) right (up (y)) = x; else left (up (y)) = x; right (x) = y; up (y) = x; } /* Turn any newly inserted node red. Then fix things up if the new * node's parent is also red. Note that this routine assumes the root * of the tree is black. */ static inline void itree_insert_fix (oc *r, oc x, const int os) { oc y; lcolor (x) = RED; while (color (up (x)) == RED) { oc gp = up (up (x)); if (up (x) == left (gp)) { y = right (gp); if (color (y) == RED) { lcolor (up (x)) = BLACK; lcolor (y) = BLACK; lcolor (gp) = RED; x = gp; } else { if (x == right (up (x))) { x = up (x); itree_left_rotate (r, x, os); } lcolor (up (x)) = BLACK; lcolor (up (up (x))) = RED; itree_right_rotate (r, up (up (x)), os); } } else { y = left (gp); if (color (y) == RED) { lcolor (up (x)) = BLACK; lcolor (y) = BLACK; lcolor (gp) = RED; x = gp; } else { if (x == left (up (x))) { x = up (x); itree_right_rotate (r, x, os); } lcolor (up (x)) = BLACK; lcolor (up (up (x))) = RED; itree_left_rotate (r, up (up (x)), os); } } } lcolor (*r) = BLACK; } void itree_insert (oc *r, oc z, const int os, int (*cmpfn) (void *, oc, oc), void *cmparg) { oc y, x; int cmpres = 0; left (z) = right (z) = y = NULL; for (x = *r; x; x = cmpres < 0 ? left (x) : right (x)) { y = x; cmpres = cmpfn (cmparg, z, x); } up (z) = y; if (!y) *r = z; else if (cmpres < 0) left (y) = z; else right (y) = z; itree_insert_fix (r, z, os); } static inline oc itree_minimum (oc x, const int os) { oc y; while ((y = left (x))) x = y; return x; } oc itree_successor (oc x, const int os) { oc y; if ((y = right (x))) return itree_minimum (y, os); for (y = up (x); y && x == right (y); y = up (y)) x = y; return y; } static inline oc itree_maximum (oc x, const int os) { oc y; while ((y = right (x))) x = y; return x; } oc itree_predecessor (oc x, const int os) { oc y; if ((y = left (x))) return itree_maximum (y, os); for (y = up (x); y && x == left (y); y = up (y)) x = y; return y; } static inline void itree_delete_fixup (oc *r, oc x, oc p, const int os) { oc w; assert (!x || up (x) == p); while (x != *r && color (x) == BLACK) { if (x) p = up (x); if (x == left (p)) { w = right (p); if (color (w) == RED) { lcolor (w) = BLACK; lcolor (p) = RED; itree_left_rotate (r, p, os); w = right (p); } if (color (left (w)) == BLACK && color (right (w)) == BLACK) { lcolor (w) = RED; x = p; } else { if (color (right (w)) == BLACK) { lcolor (left (w)) = BLACK; lcolor (w) = RED; itree_right_rotate (r, w, os); w = right (p); } lcolor (w) = color (p); lcolor (p) = BLACK; lcolor (right (w)) = BLACK; itree_left_rotate (r, p, os); x = *r; } } else { w = left (p); if (color (w) == RED) { lcolor (w) = BLACK; lcolor (p) = RED; itree_right_rotate (r, p, os); w = left (p); } if (color (right (w)) == BLACK && color (left (w)) == BLACK) { lcolor (w) = RED; x = p; } else { if (color (left (w)) == BLACK) { lcolor (right (w)) = BLACK; lcolor (w) = RED; itree_left_rotate (r, w, os); w = left (p); } lcolor (w) = color (p); lcolor (p) = BLACK; lcolor (left (w)) = BLACK; itree_right_rotate (r, p, os); x = *r; } } } if (x) lcolor (x) = BLACK; } void itree_delete (oc *r, oc z, const int os) { oc x, y, p; enum itree_color c; y = left (z) && right (z) ? itree_successor (z, os) : z; p = up (y); if ((x = left (y)) || (x = right (y))) up (x) = p; if (!p) *r = x; else if (y == left (p)) left (p) = x; else right (p) = x; c = color (y); if (y != z) { oc pz = up (z); if (pz) { if (z == left (pz)) left (pz) = y; else right (pz) = y; } else *r = y; if ((pz = left (z))) up (pz) = y; if ((pz = right (z))) up (pz) = y; *oc2rb (y, os) = *oc2rb (z, os); if (p == z) p = y; } if (c == BLACK) itree_delete_fixup (r, x, p, os); } static void itree_check_node (oc x, oc low, oc high, int bd, const int lbd, const int os, int (*cmpfn) (void *, oc, oc), void *cmparg) { /* These variables are primarily to make it easier to look at values * when debugging, hence the volatile and usused. */ volatile oc l, r, p; volatile enum itree_color cx, cl, cr, cp __attribute__((unused)); if (color (x) == BLACK) bd++; if (!x) { assert (bd == lbd); return; } cx = color (x); p = up (x); cp = color (p); l = left (x); cl = color (l); r = right (x); cr = color (r); assert (!l || up (l) == x); assert (!r || up (r) == x); assert (cx == BLACK || cx == RED); assert (cx == BLACK || (cl == BLACK && cr == BLACK)); assert (!low || cmpfn (cmparg, low, x) <= 0); assert (!high || cmpfn (cmparg, x, high) <= 0); itree_check_node (l, low, x, bd, lbd, os, cmpfn, cmparg); itree_check_node (r, x, high, bd, lbd, os, cmpfn, cmparg); } void __itree_check (oc *r, const int os, int (*cmpfn) (void *, oc, oc), void *cmparg) { oc x; int lbd = 0; assert (color (*r) == BLACK); for (x = *r; x;) { x = left (x); if (color (x) == BLACK) lbd++; } assert (!*r || !up (*r)); itree_check_node (*r, NULL, NULL, -1, lbd, os, cmpfn, cmparg); } avenger-0.8.5/libasync/dnsparse.C0000644000175000017500000004461612260422177013641 00000000000000/* $Id$ */ /* * * Copyright (C) 1998-2003 David Mazieres (dm@uun.org) * * 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 * */ /* DNS packet parsing. This code is easy to understand if and only if * you also have a copy of RFC 1035. You can get this by anonymous * ftp from, among other places, ftp.internic.net:/rfc/rfc1035.txt. */ #include "dnsparse.h" #include "arena.h" #include "vec.h" extern "C" { #ifdef NEED_DN_SKIPNAME_DECL int dn_skipname (const u_char *, const u_char *); #endif /* NEED_DN_SKIPNAME_DECL */ #ifdef NEED_DN_EXPAND_DECL int dn_expand (const u_char *, const u_char *, const u_char *, char *, int); #endif /* NEED_DN_EXPAND_DECL */ } #if 0 int dn_skipname (const u_char *icp, const u_char *eom) { const u_char *cp = icp; int n; while (cp < eom && (n = *cp++)) switch (n & 0xc0) { case 0: cp += n; break; case 0xc0: cp++; break; default: return -1; } return cp > eom ? -1 : cp - icp; } #endif dnstcppkt::dnstcppkt () : inbufsize (2048 - MALLOCRESV), inbufpos (0), inbufused (0), inbuf (static_cast (xmalloc (inbufsize))) { } dnstcppkt::~dnstcppkt () { xfree (inbuf); } void dnstcppkt::compact () { if (inbufused > 0) { if (inbufpos > inbufused) memmove (inbuf, inbuf + inbufused, inbufpos - inbufused); inbufpos -= inbufused; inbufused = 0; } } void dnstcppkt::reset () { inbufused = inbufpos = 0; outbuf.clear (); } int dnstcppkt::input (int fd) { compact (); u_int sz = pktsize (); if (sz > inbufsize) { inbufsize = sz; inbuf = static_cast (xrealloc (inbuf, inbufsize)); } if (inbufpos < sz) { errno = 0; int n = read (fd, inbuf + inbufpos, inbufsize - inbufpos); if (n > 0) inbufpos += n; else if (!n || errno != EAGAIN) return -1; } return inbufpos >= pktsize (); } int dnstcppkt::output (int fd) { if (outbuf.resid () && outbuf.output (fd) < 0) return -1; return !outbuf.resid (); } bool dnstcppkt::getpkt (u_char **pp, size_t *sp) { u_int sz = pktsize (); if (sz > inbufpos - inbufused) return false; *pp = inbuf + inbufused + 2; *sp = sz - 2; inbufused += sz; return true; } void dnstcppkt::putpkt (const u_char *pkt, size_t size) { assert (size < 0x10000); u_int16_t rawsz = htons (size); outbuf.copy (&rawsz, 2); outbuf.copy (pkt, size); } char * nameset::store (str s) { char *const zero = NULL; if (u_int *pp = name2pos[s]) return zero + *pp; name2pos.insert (s, pos); char *ret = zero + pos; pos += s.len () + 1; return ret; } char * nameset::lookup (str s) const { char *const zero = NULL; const u_int *pp = name2pos[s]; assert (pp); return zero + *pp; } void nameset::put (char *dst) const { const map_t::slot *s; for (s = name2pos.first (); s; s = name2pos.next (s)) memcpy (dst + s->value, s->key.cstr (), s->key.len () + 1); } dnsparse::dnsparse (const u_char *buf, size_t len, bool answer) : buf (buf), eom (buf + len), anp (NULL), error (0), hdr (len > sizeof (HEADER) ? (HEADER *) buf : NULL), ancount (hdr ? ntohs (hdr->ancount) : 0), nscount (hdr ? ntohs (hdr->nscount) : 0), arcount (hdr ? ntohs (hdr->arcount) : 0) { if (!hdr) error = ARERR_BADRESP; else if (hdr->rcode) error = hdr->rcode; else if ((!hdr->qr && answer) || (hdr->qr && !answer)) error = ARERR_BADRESP; else if (!ntohs (hdr->qdcount)) error = ARERR_BADRESP; #if 0 else if (hdr->tc) error = ARERR_BADRESP; #endif else { const u_char *cp = getqp (); for (int i = 0, l = ntohs (hdr->qdcount); i < l; i++) { int n = dn_skipname (cp, eom); cp += n + 4; if (n < 0 || cp > eom) { error = ARERR_BADRESP; return; } } anp = cp; } } bool dnsparse::qparse (const u_char **cpp, question *qp) { const u_char *cp = *cpp; int n = dn_expand (buf, eom, cp, qp->q_name, sizeof (qp->q_name)); if (n < 0 || n >= MAXDNAME || cp + n + 4 > eom) return false; cp += n; GETSHORT (qp->q_type, cp); GETSHORT (qp->q_class, cp); *cpp = cp; return true; } bool dnsparse::qparse (question *qp) { const u_char *cp = getqp (); return cp && qparse (&cp, qp); } bool dnsparse::rrparse (const u_char **cpp, resrec *rrp) { const u_char *cp = *cpp; const u_char *e; u_int16_t rdlen; int n; if ((n = dn_expand (buf, eom, cp, rrp->rr_name, sizeof (rrp->rr_name))) < 0 || cp + n + 10 > eom) return false; cp += n; GETSHORT (rrp->rr_type, cp); GETSHORT (rrp->rr_class, cp); GETLONG (rrp->rr_ttl, cp); GETSHORT (rdlen, cp); rrp->rr_rdlen = rdlen; if ((e = cp + rdlen) > eom) return false; switch (rrp->rr_type) { case T_A: memcpy (&rrp->rr_a, cp, sizeof (rrp->rr_a)); cp += sizeof (rrp->rr_a); break; case T_NS: case T_CNAME: case T_DNAME: case T_PTR: if ((n = dn_expand (buf, eom, cp, rrp->rr_cname, sizeof (rrp->rr_cname))) < 0) return false; cp += n; break; case T_MX: case T_AFSDB: if (rdlen < 2) return false; GETSHORT (rrp->rr_mx.mx_pref, cp); if ((n = dn_expand (buf, eom, cp, rrp->rr_mx.mx_exch, sizeof (rrp->rr_mx.mx_exch))) < 0) return false; cp += n; break; case T_TXT: if (rdlen >= sizeof (rrp->rr_txt) || rdlen < 1) return false; else { char *dp = rrp->rr_txt; while (rdlen > 0) { if (*cp + 1 > rdlen) return false; memcpy (dp, cp + 1, *cp); dp += *cp; rdlen -= *cp + 1; cp += *cp + 1; } *dp++ = '\0'; } cp += rdlen; break; case T_SOA: if ((n = dn_expand (buf, eom, cp, rrp->rr_soa.soa_mname, sizeof (rrp->rr_soa.soa_mname))) < 0) return false; cp += n; if ((n = dn_expand (buf, eom, cp, rrp->rr_soa.soa_rname, sizeof (rrp->rr_soa.soa_rname))) < 0) return false; cp += n; if (cp + 20 > eom) return false; GETLONG (rrp->rr_soa.soa_serial, cp); GETLONG (rrp->rr_soa.soa_refresh, cp); GETLONG (rrp->rr_soa.soa_retry, cp); GETLONG (rrp->rr_soa.soa_expire, cp); GETLONG (rrp->rr_soa.soa_minimum, cp); break; case T_SRV: if (rdlen < 7) return false; GETSHORT (rrp->rr_srv.srv_prio, cp); GETSHORT (rrp->rr_srv.srv_weight, cp); GETSHORT (rrp->rr_srv.srv_port, cp); if ((n = dn_expand (buf, eom, cp, rrp->rr_srv.srv_target, sizeof (rrp->rr_srv.srv_target))) < 0) return false; cp += n; break; default: cp = e; break; } assert (cp == e); *cpp = cp; return true; } bool dnsparse::skipnrecs (const u_char **cpp, u_int nrec) { const u_char *cp = *cpp; while (nrec-- > 0) { int n = dn_skipname (cp, eom); cp += n; if (n < 0 || cp + 10 > eom) return false; cp += 8; u_int16_t rdlen; GETSHORT (rdlen, cp); if (rdlen > eom - cp) return false; cp += rdlen; } *cpp = cp; return true; } bool dnsparse::gethints (vec *hv, const nameset &nset) { const u_char *cp = getanp (); if (!cp || !skipnrecs (&cp, ancount + nscount)) { error = ARERR_BADRESP; return false; } for (u_int i = 0; i < arcount; i++) { resrec rr; if (!rrparse (&cp, &rr)) { error = ARERR_BADRESP; return false; } if (rr.rr_class != C_IN || !nset.present (rr.rr_name)) continue; if (rr.rr_type == T_A) { addrhint &ah = hv->push_back (); ah.h_name = nset.lookup (rr.rr_name); ah.h_addrtype = AF_INET; ah.h_length = 4; memcpy (ah.h_address, &rr.rr_a, sizeof (rr.rr_a)); bzero (ah.h_address + sizeof (rr.rr_a), sizeof (ah.h_address) - sizeof (rr.rr_a)); } } return true; } addrhint ** dnsparse::puthints (char *dst, const vec &hv, char *namebase) { addrhint **pvp = reinterpret_cast (dst); addrhint *hvp = reinterpret_cast (&pvp[hv.size () + 1]); u_int i = hv.size (); pvp[i] = NULL; assert ((void *) &hvp[i] == namebase); while (i-- > 0) { pvp[i] = &hvp[i]; hvp[i] = hv[i]; hvp[i].h_name = nameset::xlat (namebase, hvp[i].h_name); } return pvp; } /* Takes the response from an DNS query, and turns it into a * dynamically allocated hostent structure (defined in netdb.h). All * data for the hostent structure is allocated contiguously, so that * it can all be freed by simply freeing the address of the hostent * structure returned. If no addresses are returned (i.e. no A * records returned by the query), then a valid hostent will still be * returned, but with h->h_addr_list[0] will be NULL. */ ptr dnsparse::tohostent () { const u_char *cp = getanp (); arena a; vec av; char *name = NULL; char *cname = NULL; if (!cp) return NULL; for (size_t i = 0; i < ancount; i++) { resrec rr; if (!rrparse (&cp, &rr)) { error = ARERR_BADRESP; return NULL; } if (rr.rr_class == C_IN) switch (rr.rr_type) { case T_A: if (!name) name = (a.strdup) (rr.rr_name); av.push_back (rr.rr_a); break; case T_CNAME: if (!cname) cname = (a.strdup) (rr.rr_name); break; } } if (!name) { error = ARERR_NXREC; return NULL; } ref h = refcounted::alloc (sizeof (*h) + (!!cname + 2 + av.size ()) * sizeof (char *) + av.size () * sizeof (in_addr) + strlen (name) + 1 + (cname ? strlen (cname) + 1 : 0)); h->h_addrtype = AF_INET; h->h_length = sizeof (in_addr); h->h_aliases = (char **) &h[1]; h->h_addr_list = &h->h_aliases[1+!!cname]; size_t i; for (i = 0; i < av.size (); i++) { h->h_addr_list[i] = ((char *) &h->h_addr_list[1 + av.size ()] + i * sizeof (in_addr)); *(in_addr *) h->h_addr_list[i] = av[i]; } h->h_addr_list[i] = NULL; h->h_name = ((char *) &h->h_addr_list[1 + av.size ()] + i * sizeof (in_addr)); strcpy (const_cast (h->h_name), name); if (cname) { h->h_aliases[0] = const_cast (h->h_name + strlen (h->h_name) + 1); h->h_aliases[1] = NULL; strcpy (h->h_aliases[0], cname); } else h->h_aliases[0] = NULL; return h; } int dnsparse::mxrec_cmp (const void *_a, const void *_b) { const mxrec *a = (mxrec *) _a, *b = (mxrec *) _b; int d = (int) a->pref - (int) b->pref; if (d) return d; return strcasecmp (a->name, b->name); } ptr dnsparse::tomxlist () { const u_char *cp = getanp (); nameset nset; str name; char *nameptr = NULL; if (!cp) return NULL; vec mxes; for (u_int i = 0; i < ancount; i++) { resrec rr; if (!rrparse (&cp, &rr)) { error = ARERR_BADRESP; return NULL; } if (rr.rr_class == C_IN && rr.rr_type == T_MX) { u_int16_t pr = rr.rr_mx.mx_pref; if (!name) { name = rr.rr_name; nameptr = nset.store (name); } else if (strcasecmp (name, rr.rr_name)) continue; char *xp = nset.store (rr.rr_mx.mx_exch); mxrec *mp; for (mp = mxes.base (); mp < mxes.lim () && mp->name != xp; mp++) ; if (mp < mxes.lim ()) { if (pr < mp->pref) mp->pref = pr; } else { mxes.push_back ().pref = pr; mxes.back ().name = xp; } } } if (mxes.empty ()) { error = ARERR_NXREC; return NULL; } vec hints; if (!gethints (&hints, nset)) return NULL; ref mxl = refcounted::alloc (xoffsetof (mxlist, m_mxes[mxes.size ()]) + hintsize (hints.size ()) + nset.size ()); char *hintp = reinterpret_cast (&mxl->m_mxes[mxes.size ()]); char *namebase = hintp + hintsize (hints.size ()); nset.put (namebase); mxl->m_name = nset.xlat (namebase, nameptr); mxl->m_hints = puthints (hintp, hints, namebase); mxl->m_nmx = mxes.size (); for (u_int i = 0; i < mxl->m_nmx; i++) { mxl->m_mxes[i].pref = mxes[i].pref; mxl->m_mxes[i].name = nset.xlat (namebase, mxes[i].name); } if (mxl->m_nmx > 1) qsort (mxl->m_mxes, mxl->m_nmx, sizeof (mxrec), mxrec_cmp); return mxl; } int dnsparse::srvrec_cmp (const void *_a, const void *_b) { const srvrec *a = (srvrec *) _a, *b = (srvrec *) _b; if (int d = (int) a->prio - (int) b->prio) return d; return (int) b->weight - (int) a->weight; } void dnsparse::srvrec_randomize (srvrec *base, srvrec *last) { qsort (base, last - base, sizeof (*base), &srvrec_cmp); #if 0 for (srvrec *x = base; x < last; x++) warn ("DBG: %3d %3d %5d %s\n", x->prio, x->weight, x->port, x->name); #endif while (base < last) { srvrec *lastprio = base; u_int totweight; /* It's not clear from RFC 2782 if we need to randomize multiple * records with weight 0 at the same priority. We do it anyway * just because it might be helpful. */ if (base->weight == 0) { totweight = 1; while (++lastprio < last && lastprio->prio == base->prio) totweight++; while (base + 1 < lastprio) { u_int which = arandom () % totweight; if (which) { srvrec tmp = base[which]; base[which] = *base; *base = tmp; } base++; totweight--; } } else { totweight = lastprio->weight; while (++lastprio < last && lastprio->weight && lastprio->prio == base->prio) totweight += lastprio->weight; while (base + 1 < lastprio) { u_int32_t rndweight = arandom () % totweight + 1; srvrec *nextrec; for (nextrec = base; nextrec->weight < rndweight; nextrec++) rndweight -= nextrec->weight; srvrec tmp = *base; *base = *nextrec; *nextrec = tmp; totweight -= base++->weight; } assert (totweight == base->weight); } base++; } } ptr dnsparse::tosrvlist () { const u_char *cp = getanp (); nameset nset; str name; char *nameptr = NULL; if (!cp) return NULL; vec recs; for (u_int i = 0; i < ancount; i++) { resrec rr; if (!rrparse (&cp, &rr)) { error = ARERR_BADRESP; return NULL; } if (rr.rr_class != C_IN || rr.rr_type != T_SRV) continue; if (!name) { name = rr.rr_name; nameptr = nset.store (name); } else if (strcasecmp (name, rr.rr_name)) continue; char *tp = nset.store (rr.rr_srv.srv_target); for (int i = recs.size (); i-- > 0;) if (recs[i].prio == rr.rr_srv.srv_prio && recs[i].port == rr.rr_srv.srv_port && tp == recs[i].name) { rr.rr_srv.srv_weight += recs[i].weight; continue; } srvrec &sr = recs.push_back (); sr.prio = rr.rr_srv.srv_prio; sr.weight = rr.rr_srv.srv_weight; sr.port = rr.rr_srv.srv_port; sr.name = tp; } if (!name) { error = ARERR_NXREC; return NULL; } vec hints; if (!gethints (&hints, nset)) return NULL; srvrec_randomize (recs.base (), recs.lim ()); ref s = refcounted::alloc (xoffsetof (srvlist, s_srvs[recs.size ()]) + hintsize (hints.size ()) + nset.size ()); char *hintp = reinterpret_cast (&s->s_srvs[recs.size ()]); char *namebase = hintp + hintsize (hints.size ()); nset.put (namebase); s->s_name = nset.xlat (namebase, nameptr); s->s_hints = puthints (hintp, hints, namebase); s->s_nsrv = recs.size (); for (u_int i = 0; i < s->s_nsrv; i++) { s->s_srvs[i] = recs[i]; s->s_srvs[i].name = nset.xlat (namebase, s->s_srvs[i].name); } return s; } ptr dnsparse::totxtlist () { const u_char *cp = getanp (); arena a; vec txtv; char *name = NULL; u_int nchars = 0; if (!cp) return NULL; for (size_t i = 0; i < ancount; i++) { resrec rr; if (!rrparse (&cp, &rr)) { error = ARERR_BADRESP; return NULL; } if (rr.rr_class == C_IN && rr.rr_type == T_TXT) { if (!name) { name = (a.strdup) (rr.rr_name); nchars += strlen (name) + 1; } txtv.push_back ((a.strdup) (rr.rr_txt)); nchars += strlen (txtv.back ()) + 1; } } if (!name) { error = ARERR_NXREC; return NULL; } ref t = refcounted::alloc (xoffsetof (txtlist, t_txts[txtv.size ()]) + nchars); char *dp = (char *) &t->t_txts[txtv.size ()]; t->t_name = dp; strcpy (dp, name); dp += strlen (dp) + 1; t->t_ntxt = txtv.size (); for (u_int i = 0; i < t->t_ntxt; i++) { t->t_txts[i] = dp; strcpy (dp, txtv[i]); dp += strlen (dp) + 1; } return t; } void printaddrs (const char *msg, ptr h, int dns_errno) { char **aliases; struct in_addr **addrs; if (msg) printf ("%s (hostent):\n", msg); if (! h) { printf (" Error: %s\n", dns_strerror (dns_errno)); return; } aliases = h->h_aliases; addrs = (struct in_addr **) h->h_addr_list; printf (" Name: %s\n", h->h_name); while (*aliases) printf (" Alias: %s\n", *aliases++); while (*addrs) printf (" Address: %s\n", inet_ntoa (**addrs++)); } void printhints (addrhint **hpp) { for (; *hpp; hpp++) if ((*hpp)->h_addrtype == AF_INET) printf (" (hint: %s %s)\n", (*hpp)->h_name, inet_ntoa (inaddr_cast ((*hpp)->h_address))); } void printmxlist (const char *msg, ptr m, int dns_errno) { int i; if (msg) printf ("%s (mxlist):\n", msg); if (!m) { printf (" Error: %s\n", dns_strerror (dns_errno)); return; } printf (" Name: %s\n", m->m_name); for (i = 0; i < m->m_nmx; i++) printf (" MX: %3d %s\n", m->m_mxes[i].pref, m->m_mxes[i].name); printhints (m->m_hints); } void printsrvlist (const char *msg, ptr s, int dns_errno) { int i; if (msg) printf ("%s (srvlist):\n", msg); if (!s) { printf (" Error: %s\n", dns_strerror (dns_errno)); return; } printf (" Name: %s\n", s->s_name); for (i = 0; i < s->s_nsrv; i++) printf (" SRV: %3d %3d %3d %s\n", s->s_srvs[i].prio, s->s_srvs[i].weight, s->s_srvs[i].port, s->s_srvs[i].name); printhints (s->s_hints); } void printtxtlist (const char *msg, ptr t, int dns_errno) { if (msg) printf ("%s (txtlist):\n", msg); if (!t) { printf (" Error: %s\n", dns_strerror (dns_errno)); return; } printf (" Name: %s\n", t->t_name); for (int i = 0; i < t->t_ntxt; i++) printf (" TXT: %s\n", t->t_txts[i]); } avenger-0.8.5/libasync/ihash.h0000644000175000000120000002121712077217760013147 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ /* Template implementation of intrusive hash table. Note that while * externally this code is type safe, interally it makes use of void * * pointers and byte offsets of field structures. This permits a * single implementation of the _ihash_grow() function. */ #ifndef _IHASH_H_ #define _IHASH_H_ 1 #ifdef DMALLOC # ifndef IHASH_DEBUG # define IHASH_DEBUG 1 # endif /* !IHASH_DEBUG */ # if IHASH_DEBUG /* Check hash table consistency if check-funcs token set */ # define ihash_do_debug() (dmalloc_debug_current () & 0x4000) # include "opnew.h" # endif /* IHASH_DEBUG */ # include #endif /* DMALLOC */ #include "callback.h" #include "keyfunc.h" template class ihash_entry; template T::*field> class ihash_core; struct _ihash_table; extern void _ihash_grow (_ihash_table *, const size_t); struct _ihash_entry { void *next; void **pprev; hash_t val; }; /* The template is for consistency accross all interfaces. We don't * actually need it. */ template #ifndef NO_TEMPLATE_FRIENDS class #else /* NO_TEMPLATE_FRIENDS */ struct #endif /* NO_TEMPLATE_FRIENDS */ ihash_entry : _ihash_entry { #ifndef NO_TEMPLATE_FRIENDS template U::*field> friend class ihash_core; // template T::*field> friend class ihash_core; #endif /* NO_TEMPLATE_FRIENDS */ }; struct _ihash_table { size_t buckets; size_t entries; void **tab; }; template T::*field> class ihash_core { _ihash_table t; protected: void init () { t.buckets = t.entries = 0; t.tab = NULL; _ihash_grow (&t, (size_t) &(((T *) 0)->*field)); } ihash_core () { init (); } bool present (T *elm) { for (T *e = lookup_val ((elm->*field).val); e; e = next_val (e)) if (e == elm) return true; return false; } void _check () { #if IHASH_DEBUG if (ihash_do_debug ()) { size_t s = 0; for (size_t n = 0; n < t.buckets; n++) for (T *e = (T *) t.tab[n], *ne; e; e = ne) { ne = (T *) (e->*field).next; assert (n == (e->*field).val % t.buckets); assert (ne != e); s++; } assert (s == t.entries); } #endif /* IHASH_DEBUG */ } void insert_val (T *elm, hash_t hval) { #if IHASH_DEBUG if (ihash_do_debug () && present (elm)) panic ("ihash_core(%s)::insert_val: element already in hash table\n", typeid (ihash_core).name ()); #endif /* IHASH_DEBUG */ _check (); if (++t.entries >= t.buckets) _ihash_grow (&t, (size_t) (_ihash_entry *) &(((T *) 0)->*field)); (elm->*field).val = hval; size_t bn = hval % t.buckets; T *np; if ((np = (T *) t.tab[bn])) (np->*field).pprev = &(elm->*field).next; (elm->*field).next = np; (elm->*field).pprev = &t.tab[bn]; t.tab[bn] = elm; _check (); } T *lookup_val (hash_t hval) const { T *elm; for (elm = (T *) t.tab[hval % t.buckets]; elm && (elm->*field).val != hval; elm = (T *) (elm->*field).next) ; return elm; } static T *next_val (T *elm) { hash_t hval = (elm->*field).val; while ((elm = (T *) (elm->*field).next) && (elm->*field).val != hval) ; return elm; } public: void clear () { delete[] t.tab; init (); } ~ihash_core () { delete[] t.tab; } void deleteall () { for (size_t i = 0; i < t.buckets; i++) for (T *n = (T *) t.tab[i], *nn; n; n = nn) { nn = (T *) (n->*field).next; delete n; } clear (); } size_t size () const { return t.entries; } bool constructed () const { return t.buckets > 0; } void remove (T *elm) { #if IHASH_DEBUG if (ihash_do_debug () && !present (elm)) panic ("ihash_core(%s)::remove: element not in hash table\n", typeid (ihash_core).name ()); #endif /* IHASH_DEBUG */ _check (); t.entries--; if ((elm->*field).next) (((T *) (elm->*field).next)->*field).pprev = (elm->*field).pprev; *(elm->*field).pprev = (elm->*field).next; } T *first () const { if (t.entries) for (size_t i = 0; i < t.buckets; i++) if (t.tab[i]) return (T *) t.tab[i]; return NULL; } T *next (const T *n) const { if ((n->*field).next) return (T *) (n->*field).next; for (size_t i = (n->*field).val % t.buckets; ++i < t.buckets;) if (t.tab[i]) return (T *) t.tab[i]; return NULL; } void traverse (typename callback::ref cb) { for (size_t i = 0; i < t.buckets; i++) for (T *n = (T *) t.tab[i], *nn; n; n = nn) { nn = (T *) (n->*field).next; (*cb) (n); } } void traverse (typename callback::ref cb) const { for (size_t i = 0; i < t.buckets; i++) for (T *n = (T *) t.tab[i], *nn; n; n = nn) { nn = (T *) (n->*field).next; (*cb) (*n); } } void traverse (void (T::*fn) ()) { for (size_t i = 0; i < t.buckets; i++) for (T *n = (T *) t.tab[i], *nn; n; n = nn) { nn = (T *) (n->*field).next; (n->*fn) (); } } private: /* No copying */ ihash_core (const ihash_core &); ihash_core &operator = (const ihash_core &); }; template V::*field, class H = hashfn, class E = equals > class ihash : public ihash_core { const E eq; const H hash; public: ihash () : eq (E ()), hash (H ()) {} ihash (const E &e, const H &h) : eq (e), hash (h) {} void insert (V *elm) { ihash::insert_val (elm, hash (elm->*key)); } #if 0 template V *operator[] (const T &k) const { #else V *operator[] (const K &k) const { #endif V *v; for (v = this->lookup_val (hash (k)); v && !eq (k, v->*key); v = this->next_val (v)) ; return v; } V *nextkeq (V *v) { const K &k = v->*key; while ((v = this->next_val (v)) && !eq (k, v->*key)) ; return v; }; }; template V::*field, class H = hash2fn, class E1 = equals, class E2 = equals > class ihash2 : public ihash_core { const E1 eq1; const E2 eq2; const H hash; public: ihash2 () {} ihash2 (const E1 &e1, const E2 &e2, const H &h) : eq1 (e1), eq2 (e2), hash (h) {} void insert (V *elm) { insert_val (elm, hash (elm->*key1, elm->*key2)); } V *operator() (const K1 &k1, const K2 &k2) const { V *v; for (v = lookup_val (hash (k1, k2)); v && !(eq1 (k1, v->*key1) && eq2 (k2, v->*key2)); v = next_val (v)) ; return v; } V *nextkeq (V *v) { const K1 &k1 = v->*key1; const K1 &k2 = v->*key2; while ((v = next_val (v)) && !(eq1 (k1, v->*key1) && eq2 (k2, v->*key2))) ; return v; }; }; template V::*field, class H = hashfn, class E = equals > class shash : public ihash_core { const E eq; const H hash; public: shash () {} shash (const E &e, const H &h) : eq (e), hash (h) {} void insert (V *elm) { insert_val (elm, hash (*elm)); } V *operator[] (const V &k) const { V *v; for (v = lookup_val (hash (k)); v && !eq (k, *v); v = next_val (v)) ; return v; } V *nextkeq (V *v) { const V &k = *v; while ((v = next_val (v)) && !eq (k, *v)) ; return v; } }; template struct keyfn { keyfn () {} const K & operator() (V *v) const { assert (false); return K (); } }; template V::*field, class F = keyfn, class H = hashfn, class E = equals > class fhash : public ihash_core { const E eq; const H hash; const F keyfn; public: fhash () {} fhash (const E &e, const H &h, const F &k) : eq (e), hash (h), keyfn (k) {} void insert (V *elm) { insert_val (elm, hash (keyfn (elm))); } V *operator[] (const K &k) const { V *v; for (v = lookup_val (hash (k)); v && !eq (k, keyfn (v)); v = next_val (v)) ; return v; } V *nextkeq (V *v) { const K &k = keyfn (v); while ((v = next_val (v)) && !eq (k, keyfn (v))) ; return v; } }; #endif /* !_IHASH_H_ */ avenger-0.8.5/libasync/str.h0000644000175000017500000002704211221237220012656 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_STR_H_ #define _ASYNC_STR_H_ 1 #include "suio++.h" #include "keyfunc.h" #include "stllike.h" #include "refcnt.h" extern void (*const strobj_opdel) (void *); class mstr; class strbuf; class strobj { friend class strobjptr; u_int refcnt; strobj () : refcnt (0), delfn (strobj_opdel) {} void refcount_inc () { refcnt++; } void refcount_dec () { if (!--refcnt) delfn (this); } public: size_t len; void (*delfn) (void *); #if __GNUC__ >= 2 char contents[0]; #endif /* gcc2 */ char *dat () { return (char *) this + sizeof (*this); } static strobj *alloc (size_t n) { return new (opnew (n + sizeof (strobj))) strobj; } }; class strobjptr { strobj *p; public: strobjptr () : p (NULL) {} strobjptr (strobj *pp) : p (pp) { if (p) p->refcount_inc (); } strobjptr (const strobjptr &b) : p (b.p) { if (p) p->refcount_inc (); } ~strobjptr () { if (p) p->refcount_dec (); } strobjptr &operator= (strobj *pp) { if (pp) pp->refcount_inc (); if (p) p->refcount_dec (); p = pp; return *this; } strobjptr &operator= (const strobjptr &b) { return *this = b.p; } operator bool () const { return p; } strobj *operator-> () const { return p; } void *Xleak () const { if (p) p->refcount_inc (); return p; } static void Xplug (void *p) { if (p) static_cast (p)->refcount_dec (); } }; class str { // friend const strbuf &strbuf_cat (const strbuf &, const str &); friend void suio_print (suio *, const str &); friend class str_init; friend class mstr; friend class bssstr; strobjptr b; static strobj *buf2strobj (const char *buf, size_t len) { strobj *b = strobj::alloc (1 + len); b->len = len; memcpy (b->dat (), buf, len); b->dat ()[len] = '\0'; return b; } strobj *iov2strobj (const iovec *iov, int cnt); explicit str (__bss_init) {} public: str () {} str (const str &s) : b (s.b) {} str (const char *p) { b = p ? buf2strobj (p, strlen (p)) : NULL; } str (const strbuf &b); explicit str (const suio &u) : b (iov2strobj (u.iov (), u.iovcnt ())) {} str (const char *buf, size_t len) : b (buf2strobj (buf, len)) {} str (const iovec *iov, int cnt) { setiov (iov, cnt); } str (mstr &); str &operator= (const str &s) { b = s.b; return *this; } str &operator= (const char *p) { if (p) setbuf (p, strlen (p)); else b = NULL; return *this; } str &operator= (const strbuf &b); str &operator= (mstr &m); str &setbuf (const char *buf, size_t len) { b = buf2strobj (buf, len); return *this; } str &setiov (const iovec *iov, int cnt) { b = iov2strobj (iov, cnt); return *this; } size_t len () const { return b->len; } const char *cstr () const { return b ? b->dat () : NULL; } operator const char *() const { return cstr (); } char operator[] (ptrdiff_t n) const { #ifdef CHECK_BOUNDS assert (size_t (n) <= b->len); #endif /* CHECK_BOUNDS */ return b->dat ()[n]; } int cmp (const str &s) const { if (int r = memcmp (cstr (), s.cstr (), min (len (), s.len ()))) return r; return len () - s.len (); } int cmp (const char *p) const { const char *s = cstr (); const char *e = s + len (); while (*s == *p) if (!*p++) return e - s; else if (s++ == e) return -1; return (u_char) *s - (u_char) *p; } bool operator== (const str &s) const { return len () == s.len () && !memcmp (cstr (), s.cstr (), len ()); } bool operator!= (const str &s) const { return len () != s.len () || memcmp (cstr (), s.cstr (), len ()); } bool operator< (const str &s) const { return cmp (s) < 0; } bool operator<= (const str &s) const { return cmp (s) <= 0; } bool operator> (const str &s) const { return cmp (s) > 0; } bool operator>= (const str &s) const { return cmp (s) >= 0; } bool operator== (const char *p) const { return !cmp (p); } bool operator!= (const char *p) const { return cmp (p); } operator hash_t () const { return hash_bytes (cstr (), len ()); } static void Xvstomp (const str *sp, void (*dfn) (void *)) { assert (sp->b->delfn == strobj_opdel); sp->b->delfn = dfn; } }; struct bssstr : public str { public: bssstr () : str (__bss_init ()) {} ~bssstr () { assert (globaldestruction); b.Xleak (); } str &operator= (const str &s) { return str::operator= (s); } str &operator= (const bssstr &s) { return str::operator= (s); } }; inline bool operator== (const char *p, const str &s) { return s == p; } inline bool operator!= (const char *p, const str &s) { return s != p; } template<> struct compare { compare () {} int operator () (const str &a, const str &b) const { return a.cmp (b); } int operator () (const str &a, const char *b) const { return a.cmp (b); } int operator () (const char *a, const str &b) const { return -b.cmp (a); } int operator () (const char *a, const char *b) const { return strcmp (a, b); } }; template<> struct equals { equals () {} int operator () (const str &a, const str &b) const { return a == b; } int operator () (const str &a, const char *b) const { return a == b; } int operator () (const char *a, const str &b) const { return a == b; } int operator () (const char *a, const char *b) const { return !strcmp (a, b); } }; template<> struct hashfn { hashfn () {} hash_t operator () (const str &s) const { return s; } hash_t operator () (const char *p) const { return hash_string (p); } }; class mstr { friend class str; mstr (const mstr &); mstr &operator= (const mstr &); protected: strobjptr b; mstr () {} public: explicit mstr (size_t n) : b (strobj::alloc (n + 1)) { b->len = n; } void setlen (size_t n) { assert (n <= b->len); b->len = n; } size_t len () const { return b->len; } const char *cstr () const { return b->dat (); } operator const char *() const { return cstr (); } char *cstr () { return b->dat (); } operator char *() { return cstr (); } }; inline str::str (mstr &m) : b (m.b) { b->dat ()[b->len] = '\0'; m.b = NULL; // Destroy mutable string } inline str & str::operator= (mstr &m) { b = m.b; b->dat ()[b->len] = '\0'; m.b = NULL; // Destroy mutable string return *this; } void suio_print (suio *uio, const str &s); str suio_getline (suio *uio); class strbuf { friend inline const strbuf &strbuf_cat (const strbuf &, const strbuf &); strbuf &operator= (const strbuf &); protected: const ref uio; public: strbuf () : uio (New refcounted) {} strbuf (const str &s) : uio (New refcounted) { suio_print (uio, s); } strbuf (const strbuf &b) : uio (b.uio) {} explicit strbuf (const ref &u) : uio (u) {} explicit strbuf (const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); const strbuf &fmt (const char *, ...) const __attribute__ ((format (printf, 2, 3))); const strbuf &vfmt (const char *fmt, va_list ap) const { suio_vuprintf (uio, fmt, ap); return *this; } const strbuf &buf (const char *buf, size_t len) const { suio_printcheck (uio, buf, len); return *this; } /* gcc bug requires explicit declarations for const char * */ const strbuf &cat (const char *p, bool copy = true) const { if (copy) uio->copy (p, strlen (p)); else suio_printcheck (uio, p, strlen (p)); return *this; } // const strbuf &operator<< (const char *p) const { return cat (p); } template const strbuf &cat (const A1 &a1) const { return strbuf_cat (*this, a1); } template const strbuf &cat (const A1 &a1, const A2 &a2) const { return strbuf_cat (*this, a1, a2); } const iovec *iov () const { return uio->iov (); } size_t iovcnt () const { return uio->iovcnt (); } suio *tosuio () const { return uio; } }; inline str::str (const strbuf &sb) : b (iov2strobj (sb.iov (), sb.iovcnt ())) { } inline str & str::operator= (const strbuf &sb) { setiov (sb.iov (), sb.iovcnt ()); return *this; } inline const strbuf & strbuf_cat (const strbuf &b, const strbuf &b2) { b.uio->copyu (b2.uio); return b; } inline const strbuf & strbuf_cat (const strbuf &b, const str &s) { suio *uio = b.tosuio (); suio_print (uio, s); return b; } const strbuf &strbuf_cat (const strbuf &b, const char *p, bool copy = true); #define STRBUFOP(arg, op) \ inline const strbuf & \ strbuf_cat (const strbuf &b, arg) \ { \ op; \ return b; \ } STRBUFOP (int n, b.fmt ("%d", n)) STRBUFOP (u_int n, b.fmt ("%u", n)) STRBUFOP (long n, b.fmt ("%ld", n)) STRBUFOP (u_long n, b.fmt ("%lu", n)) #if SIZEOF_LONG_LONG > 0 STRBUFOP (long long n, b.fmt ("%qd", n)) STRBUFOP (unsigned long long n, b.fmt ("%qu", n)) #endif /* SIZEOF_LONG_LONG > 0 */ #undef STRBUFOP template class strbufcatobj { const A &a; const B &b; public: const strbuf &cat (const strbuf &sb) const { return sb.cat (a, b); } strbufcatobj (const A &aa, const B &bb) : a (aa), b (bb) {} }; template class strbufcatobj { const A &a; public: const strbuf &cat (const strbuf &sb) const { return sb.cat (a); } strbufcatobj (const A &aa) : a (aa) {} }; template const strbuf & strbuf_cat (const strbuf &sb, const strbufcatobj &o) { return o.cat (sb); } template inline strbufcatobj cat (const A &a, const B &b) { return strbufcatobj (a, b); } template inline strbufcatobj cat (const A &a) { return strbufcatobj (a); } class hexdump { friend const strbuf &strbuf_cat (const strbuf &, const hexdump &); const void *const buf; const size_t len; public: hexdump (const void *b, size_t l) : buf (b), len (l) {} }; inline const strbuf & strbuf_cat (const strbuf &sb, const hexdump &hd) { const u_char *p = static_cast (hd.buf); const u_char *end = p + hd.len; while (p < end) sb.fmt ("%02x", *p++); return sb; } template inline const strbuf & operator<< (const strbuf &sb, const T &a) { return strbuf_cat (sb, a); } inline const strbuf & operator<< (const strbuf &sb, const str &s) { suio_print (sb.tosuio (), s); return sb; } #if 0 /* XXX - work around g++ bug */ inline const strbuf & operator<< (const strbuf &sb, const char *a) { return strbuf_cat (sb, a); } #endif /* XXX - compilation time goes through the roof when this is inlined */ /* XXX - work around g++ bug */ const strbuf &operator<< (const strbuf &sb, const char *a); #if 0 template inline const strbuf operator<< (const str &s, const T &t) { return strbuf (s).cat (t); } #endif /* XXX - work around g++ bug */ const strbuf operator<< (const str &s, const char *a); inline const strbuf operator<< (const str &s1, const str &s2) { return strbuf (s1).cat (s2); } inline str substr (const str &s, size_t pos, size_t len = (size_t) -1) { if (pos >= s.len ()) return ""; if (len > s.len () - pos) len = s.len () - pos; return str (s.cstr () + pos, len); } #endif /* !_ASYNC_STR_H_ */ avenger-0.8.5/libasync/sysconf.h0000644000175000017500000004067411340313303013537 00000000000000/* $Id: sysconf.h,v 1.69 2009/05/11 22:09:50 dm Exp $ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_SYSCONF_H_ #define _ASYNC_SYSCONF_H_ 1 #if __linux /* This seems to be required for struct ucred */ # define _GNU_SOURCE 1 #endif /* __gnu_linux */ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifdef HAVE_CONFIG_H #include #endif /* HAVE_CONFIG_H */ #include "autoconf.h" #ifdef __cplusplus #undef inline #undef const #endif /* __cplusplus */ #if __GNUC__ < 2 /* Linux has some pretty broken header files */ #undef _EXTERN_INLINE #define _EXTERN_INLINE static inline #endif /* !gcc2 */ #define PORTMAP #ifdef TIME_WITH_SYS_TIME # include # include #elif defined (HAVE_SYS_TIME_H) # include #else /* !TIME_WITH_SYS_TIME && !HAVE_SYS_TIME_H */ # include #endif /* !TIME_WITH_SYS_TIME && !HAVE_SYS_TIME_H */ #ifdef HAVE_TIMES # include #endif /* HAVE_TIMES */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_SYS_SOCKIO_H # include #endif /* HAVE_SYS_SOCKIO_H */ #ifdef HAVE_SYS_FILIO_H # include #endif /* HAVE_SYS_FILIO_H */ #ifdef HAVE_SYS_FILE_H # include #endif /* HAVE_SYS_FILE_H */ #if HAVE_SYS_WAIT_H # include #endif #ifndef WEXITSTATUS # define WEXITSTATUS(stat_val) ((unsigned)(stat_val) >> 8) #endif #ifndef WIFEXITED # define WIFEXITED(stat_val) (((stat_val) & 255) == 0) #endif #include #ifdef HAVE_SYS_RUSAGE_H # include #endif /* HAVE_SYS_RUSAGE_H */ #ifdef NEED_GETRUSAGE_DECL int getrusage (int who, struct rusage *rusage); #endif /* NEED_GETRUSAGE_DECL */ #ifdef NEED_FCHDIR_DECL int fchdir (int); #endif /* NEED_FCHDIR_DECL */ #include #include #include #include #include #ifdef SETGROUPS_NEEDS_GRP_H #include #endif /* SETGROUPS_NEEDS_GRP_H */ #include /* Some systems have an ip_opts field in the ip_opts structure */ #define __concatenate(t1, t2) t1##t2 #define concatenate(t1, t2) __concatenate(t1, t2) #define ip_opts concatenate(ip_opts_kludge, __LINE__) #include #undef __concatenate #undef concatenate #undef ip_opts #include #if defined(PYMALLOC) && defined(DMALLOC) # undef DMALLOC #endif /* PYMALLOC && DMALLOC */ #if STDC_HEADERS # include # ifndef bzero # if __GNUC__ >= 4 /* GCC 4 warns about zero length memset, but this is not an issue * with bzero. This hack works around the problem. */ static inline void __my_gcc4_bzero (void *a, size_t b) { if (b) memset (a, 0, b); } # define bzero(a, b) __my_gcc4_bzero(a, b) # else # define bzero(a,b) memset((a), 0, (b)) # endif /* __GNUC__ < 4 */ # endif /* !bzero */ #else /* !STDC_HEADERS */ # ifndef DMALLOC # ifndef HAVE_STRCHR # define strchr index # define strrchr rindex # endif /* !HAVE_STRCHR */ # ifdef __cplusplus char *strchr (const char *, int); char *strrchr (const char *, int); # else /* !__cplusplus */ char *strchr (); char *strrchr (); # endif /* !__cplusplus */ # ifdef HAVE_MEMCPY # define bzero(a,b) memset((a), 0, (b)) # else /* !HAVE_MEMCPY */ # define memcpy(d, s, n) bcopy ((s), (d), (n)) # define memmove(d, s, n) bcopy ((s), (d), (n)) # endif /* !HAVE_MEMCPY */ # endif /* !DMALLOC || PYMALLOC */ #endif #if defined (__linux__) && !defined (__GNUC__) /* GNU libc has some really really broken header files. */ # ifdef __cplusplus extern "C++" { inline bool operator== (dev_t d1, dev_t d2) { return !memcmp (&d1, &d2, sizeof (d1)); } inline bool operator!= (dev_t d1, dev_t d2) { return memcmp (&d1, &d2, sizeof (d1)); } } # endif /* __cplusplus */ #endif /* __linux__ && !__GNUC__ */ #ifndef UIO_MAXIOV #define UIO_MAXIOV 16 #endif /* UIO_MAXIOV */ /* * Compiler/arhcitecture attributes */ #if __GNUC__ >= 2 # ifdef __cplusplus # if __GNUC__ == 2 && __GNUC_MINOR__ < 91 /* !egcs */ # define NO_TEMPLATE_FRIENDS 1 # endif /* !egcs */ # define PRIVDEST friend class stupid_gcc_disallows_private_destructors; # endif /* __cplusplus */ #else /* !gcc2 */ # ifndef __attribute__ # define __attribute__(x) # endif /* !__attribute__ */ #endif /* !gcc 2 */ #if __GNUC__ >= 3 # define Xtmpl #else /* gcc < 3 */ # define Xtmpl template #endif /* gcc < 3 */ #ifndef PRIVDEST #define PRIVDEST /* empty */ #endif /* !PRIVDEST */ #ifndef HAVE_SSIZE_T typedef int ssize_t; #endif /* !HAVE_SSIZE_T */ #ifndef HAVE_INT32_T typedef int int32_t; #endif /* !HAVE_INT32_T */ #ifndef HAVE_U_INT32_T typedef unsigned int u_int32_t; #endif /* !HAVE_U_INT32_T */ #ifndef HAVE_U_INT16_T typedef unsigned short u_int16_t; #endif /* !HAVE_U_INT16_T */ #ifndef HAVE_U_INT8_T typedef unsigned char u_int8_t; #endif /* !HAVE_U_INT8_T */ #ifndef HAVE_MODE_T typedef unsigned short mode_t; #endif /* !HAVE_MODE_T */ #ifndef HAVE_U_CHAR typedef unsigned char u_char; #endif /* !HAVE_U_CHAR */ #ifndef HAVE_U_INT typedef unsigned int u_int; #endif /* !HAVE_U_INT */ #ifndef HAVE_U_LONG typedef unsigned long u_long; #endif /* !HAVE_U_LONG */ #ifndef HAVE_RLIM_T typedef int rlim_t; #endif /* !HAVE_RLIM_T */ #ifndef HAVE_INT64_T # if SIZEOF_LONG == 8 typedef long int64_t; # elif SIZEOF_LONG_LONG == 8 typedef long long int64_t; # else /* Can't find 64-bit type */ # error "Cannot find any 64-bit data types" # endif /* !SIZEOF_LONG_LONG */ #endif /* !HAVE_INT64_T */ #ifndef HAVE_U_INT64_T # if SIZEOF_LONG == 8 typedef unsigned long u_int64_t; # elif SIZEOF_LONG_LONG == 8 typedef unsigned long long u_int64_t; # else /* Can't find 64-bit type */ # error "Cannot find any 64-bit data types" # endif /* !SIZEOF_LONG_LONG */ # define HAVE_U_INT64_T 1 /* XXX */ #endif /* !HAVE_INT64_T */ #if SIZEOF_LONG == 8 # define INT64(n) n##L #elif SIZEOF_LONG_LONG == 8 # define INT64(n) n##LL #else /* Can't find 64-bit type */ # error "Cannot find any 64-bit data types" #endif /* !SIZEOF_LONG_LONG */ #ifdef U_INT64_T_IS_LONG_LONG # if defined (__sun__) && defined (__svr4__) # define U64F "ll" # else /* everyone else */ # define U64F "q" # endif /* everyone else */ #else /* !U_INT64_T_IS_LONG_LONG */ # define U64F "l" #endif /* !U_INT64_T_IS_LONG_LONG */ #ifdef WORDS_BIGENDIAN #define htonq(n) n #define ntohq(n) n #else /* little endian */ static inline u_int64_t htonq (u_int64_t v) { return htonl ((u_int32_t) (v >> 32)) | (u_int64_t) htonl ((u_int32_t) v) << 32; } static inline u_int64_t ntohq (u_int64_t v) { return ntohl ((u_int32_t) (v >> 32)) | (u_int64_t) ntohl ((u_int32_t) v) << 32; } #endif /* little endian */ /* * OS/library features */ #ifdef HAVE_PREAD # ifndef HAVE_PREAD_DECL ssize_t pread(int, void *, size_t, off_t); # endif /* !HAVE_PREAD_DECL */ #endif /* !HAVE_PREAD */ #ifdef HAVE_PWRITE # ifndef HAVE_PWRITE_DECL ssize_t pwrite(int, const void *, size_t, off_t); # endif /* !HAVE_PWRITE_DECL */ #endif /* !HAVE_PWRITE */ /* XXX - some OSes don't put the __attribute__ ((noreturn)) on exit * and abort. However, on some linuxes redeclaring these functions * causes compilation errors, as the originals are declared throw () * for C++. */ #ifdef __THROW void abort (void) __THROW __attribute__ ((noreturn)); void exit (int) __THROW __attribute__ ((noreturn)); #else /* !__THROW */ void abort (void) __attribute__ ((noreturn)); void exit (int) __attribute__ ((noreturn)); #endif /* !__THROW */ void _exit (int) __attribute__ ((noreturn)); #if !defined(HAVE_STRERROR) && !defined(strerror) extern int sys_nerr; extern char *sys_errlist[]; #define strerror(n) ((unsigned) (n) < sys_nerr \ ? sys_errlist[n] : "large error number") #endif /* !HAVE_STRERROR && !strerror */ #ifndef INADDR_NONE # define INADDR_NONE 0xffffffffU #endif /* !INADDR_NONE */ #ifndef HAVE_INET_ATON # define inet_aton(a,b) (((b)->s_addr = inet_addr((a))) != INADDR_NONE) #endif /* constants for flock */ #ifndef LOCK_SH # define LOCK_SH 1 /* shared lock */ # define LOCK_EX 2 /* exclusive lock */ # define LOCK_NB 4 /* don't block when locking */ # define LOCK_UN 8 /* unlock */ #endif /* !LOCK_SH */ #ifdef NEED_FLOCK_DECL int flock (int fd, int operation); #endif /* NEED_FLOCK_DECL */ #ifndef SHUT_RD # define SHUT_RD 0 # define SHUT_WR 1 # define SHUT_RDWR 2 #endif /* !SHUT_RD */ #if defined (SIGPOLL) && !defined (SIGIO) # define SIGIO SIGPOLL #endif /* SIGPOLL && !SIGIO */ #if defined (FASYNC) && !defined (O_ASYNC) # define O_ASYNC FASYNC #endif /* FASYNC && !O_ASYNC */ #ifndef MAP_FILE # define MAP_FILE 0 #endif /* !MAP_FILE */ #if defined (MS_ASYNC) || defined (MS_SYNC) # define HAVE_MSYNC_FLAGS 1 # ifndef MS_SYNC # define MS_SYNC 0 # endif /* !MS_SYNC */ # ifndef MS_ASYNC # define MS_SYNC 0 # endif /* !MS_ASYNC */ #endif /* MS_ASYNC || MS_SYNC */ /* Format specifier for printing off_t variables */ #ifdef HAVE_OFF_T_64 # define OTF "q" #else /* !HAVE_OFF_T_64 */ # define OTF "l" #endif /* !HAVE_OFF_T_64 */ /* Type of iov_base */ typedef char *iovbase_t; #ifndef HAVE_SOCKLEN_T #define socklen_t int #endif /* !HAVE_SOCKLEN_T */ #ifndef HAVE_STRUCT_SOCKADDR_STORAGE #define sockaddr_storage sockaddr #endif /* !HAVE_STRUCT_SOCKADDR_STORAGE */ #ifndef HAVE_TIMESPEC struct timespec { time_t tv_sec; long tv_nsec; }; #endif /* !HAVE_TIMESPEC */ #ifndef HAVE_ST_MTIMESPEC # ifdef HAVE_ST_MTIM # define st_mtimespec st_mtim # define HAVE_ST_MTIMESPEC 1 # endif /* HAVE_ST_MTIM */ #endif /* !HAVE_ST_MTIMESPEC */ #ifdef NEED_MKSTEMP_DECL int mkstemp (char *); #endif /* NEED_MKSTEMP_DECL */ #ifndef HAVE_CLOCK_GETTIME_DECL int clock_gettime (int, struct timespec *); #endif /* !HAVE_CLOCK_GETTIME_DECL */ #ifndef HAVE_CLOCK_GETTIME # undef CLOCK_REALTIME # undef CLOCK_VIRTUAL # undef CLOCK_PROF #endif /* !HAVE_CLOCK_GETTIME */ #ifndef CLOCK_REALTIME # define CLOCK_REALTIME 0 #endif /* !CLOCK_REALTIME */ #ifndef CLOCK_VIRTUAL # define CLOCK_VIRTUAL 1 #endif /* !CLOCK_VIRTUAL */ #ifndef CLOCK_PROF # define CLOCK_PROF 2 #endif /* !CLOCK_PROF */ #ifndef PATH_MAX # if defined (MAXPATH) # define PATH_MAX MAXPATH # elif defined (FILENAME_MAX) # define PATH_MAX FILENAME_MAX # else /* !PATH_MAX && !FILENAME_MAX */ # define PATH_MAX 1024 # endif /* !PATH_MAX && !FILENAME_MAX */ #endif /* PATH_MAX */ #ifndef HAVE_GETPEEREID # ifdef SO_PEERCRED int getpeereid (int fd, uid_t *u, gid_t *g); # define HAVE_GETPEEREID 1 # define NEED_GETPEEREID 1 # endif /* SO_PEERCRED */ #endif /* !HAVE_GETPEEREID */ /* * Debug malloc */ #define __stringify(s) #s #define stringify(s) __stringify(s) #define __FL__ __FILE__ ":" stringify (__LINE__) const char *__backtrace (const char *file, int lim); #define __BACKTRACE__ (__backtrace (__FL__, -1)) #ifdef DMALLOC #define CHECK_BOUNDS 1 #define DMALLOC_FUNC_CHECK #ifdef HAVE_MEMORY_H #include #endif /* HAVE_MEMORY_H */ #include #if DMALLOC_VERSION_MAJOR < 5 || DMALLOC_VERSION_MAJOR == 5 && DMALLOC_VERSION_MINOR < 5 #undef memcpy #define memcpy(to, from, len) \ _dmalloc_memcpy((char *) (to), (const char *) (from), len) #define memmove(to, from, len) \ _dmalloc_bcopy((const char *) (from), (char *) (to), len) #undef xstrdup #define xstrdup(__s) ((char *) dmalloc_strdup(__FILE__, __LINE__, __s, 1)) #endif /* dmalloc < 5.5 */ /* Work around Dmalloc's misunderstanding of free's definition */ #undef xfree #if DMALLOC_VERSION_MAJOR >= 5 #define _xmalloc_leap(f, l, s) \ dmalloc_malloc (f, l, s, DMALLOC_FUNC_MALLOC, 0, 1) #define _malloc_leap(f, l, s) \ dmalloc_malloc (f, l, s, DMALLOC_FUNC_MALLOC, 0, 0) #define _xfree_leap(f, l, p) dmalloc_free (f, l, p, DMALLOC_FUNC_FREE) #endif /* DMALLOC_VERSION_MAJOR >= 5 */ static inline void _xfree_wrap (const char *file, int line, void *ptr) { if (ptr) _xfree_leap(file, line, ptr); } static inline void xfree (void *ptr) { if (ptr) _xfree_leap("unknown file", 0, ptr); } #define xfree(ptr) _xfree_wrap(__FILE__, __LINE__, ptr) const char *stktrace (const char *file); extern int stktrace_record; #define txmalloc(size) _xmalloc_leap (stktrace (__FILE__), __LINE__, size) #else /* !DMALLOC */ void *xmalloc (size_t); void *xrealloc (void *, size_t); #ifdef PYMALLOC # include # define xfree PyMem_Free #else /* !PYMALLOC (i.e., the default condition) */ # define xfree free #endif /* PYMALLOC */ char *xstrdup (const char *s); #define txmalloc(size) xmalloc (size) #endif /* !DMALLOC */ #ifndef HAVE_STRCASECMP #ifdef DMALLOC /* These funcitons are only implemented on systems that actually have * strcasecmp. */ #undef strcasecmp #undef strncasecmp #endif /* DMALLOC */ int strcasecmp (const char *, const char *); int strncasecmp (const char *, const char *, int); #endif /* HAVE_STRCASECMP */ /* * Other random stuff */ /* Some versions of linux have a weird offsetof definition */ #define xoffsetof(type, member) ((size_t)(&((type *)0)->member)) #ifdef __cplusplus /* Egcs g++ without '-ansi' has some strange ideas about what NULL * should be. */ #undef NULL #define NULL 0 #undef __null #define __null 0 #endif /* __cplusplus */ #undef sun extern void panic (const char *msg, ...) __attribute__ ((noreturn, format (printf, 1, 2))); /* smprintf is like snprintf, except where the buffer size is supposed * to be adequate. */ #ifdef HAVE_SNPRINTF # if __GNUC__ >= 2 && defined (DMALLOC) # define smprintf(__smp_buf, __smp__len, __smp_rest...) \ ({ \ size_t __smp_len = (__smp__len); \ size_t __smp_actual = snprintf (__smp_buf, __smp_len, __smp_rest); \ if (__smp_actual >= __smp_len) \ panic ("buffer overrun at %s\n", __FL__); \ __smp_actual; \ }) # else /* !gcc2 or !DMALLOC */ # define smprintf snprintf # endif /* !gcc2 or !DMALLOC */ #else /* !HAVE_SNPRINTF */ # if __GNUC__ >= 2 && defined (DMALLOC) # define smprintf(__smp_buf, __smp__len, __smp_rest...) \ ({ \ size_t __smp_len = (__smp__len); \ size_t __smp_actual = sprintf (__smp_buf, __smp_rest); \ if (__smp_actual >= __smp_len) \ panic ("buffer overrun at %s\n", __FL__); \ __smp_actual; \ }) # else /* !gcc2 or !DMALLOC */ # define smprintf(__smp_buf, __smp_len, ...) sprintf (__smp_buf, __VA_ARGS__) # endif /* !gcc2 or !DMALLOC */ #endif /* !HAVE_SNPRINTF */ #define MALLOCRESV 16 /* Best to allocate 2^n - MALLOCRESV bytes */ #ifndef MAINTAINER # define MAINTAINER 1 #elif !MAINTAINER # undef MAINTAINER #endif /* !MAINTAINER */ /* * Setuid or setgid programs must contain * * int suidprotect = 1; * * in the file that contains main. Otherwise, bad things may happen * in global constructors, even before the first line of main gets to * execute. In C++, clearing dangerous environment variables in main * is insecure, as it may already be too late. * * The function suidsafe() returns 1 if setuidprotect was not * initialized to 1 or the program was not setuid or the program was * run by root. Otherwise, it returns 0. * * The function safegetenv() returns the output of getenv unless * suidsafe() is 1, in which case it always returns NULL. */ #ifdef __cplusplus extern "C" #endif /* __cplusplus */ int suidprotect; /* Set at compile time in suid programs */ #ifdef __cplusplus extern "C" #endif /* __cplusplus */ int execprotect; /* Set if program will drop privileges */ int suidsafe (void); int execsafe (void); char *safegetenv (const char *); #ifdef PUTENV_COPIES_ARGUMENT #define xputenv putenv #else /* !PUTENV_COPIES_ARGUMENT */ extern int xputenv (const char *s); #endif /* !PUTENV_COPIES_ARGUMENT */ #ifndef HAVE_UNSETENV void unsetenv (const char *); #endif /* !HAVE_UNSETENV */ #ifdef __cplusplus } /* Work around warn_unused_result for places where you really don't * want to use the result. */ template inline void use (T) { } #endif /* __cplusplus */ #endif /* !_ASYNC_SYSCONF_H_ */ avenger-0.8.5/libasync/clock_gettime.c0000644000175000017500000000325111221237220014646 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "sysconf.h" #ifndef HAVE_CLOCK_GETTIME #include int clock_gettime (int id, struct timespec *tp) { struct timeval tv; struct rusage ru; switch (id) { case CLOCK_REALTIME: if (gettimeofday (&tv, NULL) < 0) return -1; tp->tv_sec = tv.tv_sec; tp->tv_nsec = tv.tv_usec * 1000; return 0; case CLOCK_VIRTUAL: if (getrusage (RUSAGE_SELF, &ru) < 0) return -1; tp->tv_sec = ru.ru_utime.tv_sec; tp->tv_nsec = ru.ru_utime.tv_usec * 1000; return 0; case CLOCK_PROF: if (getrusage (RUSAGE_SELF, &ru) < 0) return -1; tp->tv_sec = (ru.ru_utime.tv_sec + ru.ru_stime.tv_sec); tp->tv_nsec = (ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) * 1000; while (tp->tv_nsec > 1000000000) { tp->tv_sec++; tp->tv_nsec -= 1000000000; } return 0; default: errno = EINVAL; return -1; } } #endif /* !HAVE_CLOCK_GETTIME */ avenger-0.8.5/libasync/ihash.C0000644000175000017500000000364312260422177013111 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "amisc.h" #include "ihash.h" #include "msb.h" /* Some prime numbers <= powers of 2 */ const u_int exp2primes[33] = { 0x1, /* place holder */ 0x2, 0x3, 0x7, 0xd, 0x1f, 0x3d, 0x7f, 0xfb, 0x1fd, 0x3fd, 0x7f7, 0xffd, 0x1fff, 0x3ffd, 0x7fed, 0xfff1, 0x1ffff, 0x3fffb, 0x7ffff, 0xffffd, 0x1ffff7, 0x3ffffd, 0x7ffff1, 0xfffffd, 0x1ffffd9, 0x3fffffb, 0x7ffffd9, 0xfffffc7, 0x1ffffffd, 0x3fffffdd, 0x7fffffff, 0xfffffffb, }; #define hteof(p) ((_ihash_entry *) ((char *) (p) + eos)) void _ihash_grow (_ihash_table *htp, const size_t eos) { u_int nbuckets; void **ntab; void *p, *np; size_t i; nbuckets = exp2primes[log2c(htp->buckets)+1]; if (nbuckets < 3) nbuckets = 3; ntab = New void *[nbuckets]; bzero (ntab, nbuckets * sizeof (*ntab)); for (i = 0; i < htp->buckets; i++) for (p = htp->tab[i]; p; p = np) { _ihash_entry *htep = hteof (p); size_t ni = htep->val % nbuckets; np = htep->next; htep->next = ntab[ni]; htep->pprev = &ntab[ni]; if (ntab[ni]) hteof(ntab[ni])->pprev = &htep->next; ntab[ni] = p; } delete[] htp->tab; htp->tab = ntab; htp->buckets = nbuckets; } avenger-0.8.5/libasync/parseopt.C0000644000175000017500000001231612260422177013647 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "amisc.h" #include "parseopt.h" static char errbuf[1] = ""; char *parseargs::errorbuf = errbuf; static inline int isspc (char c) { return c == ' ' || c == '\t' || c == '\n'; } static inline int isspcnnl (char c) { return c == ' ' || c == '\t'; } void parseargs::skipblanks () { bool bol = true; while (p < lim) { if (bol && *p == '#') { while (p < lim && *p != '\n') p++; if (p < lim) { lineno++; p++; } continue; } if (isspcnnl (*p)) { bol = false; p++; } else if (*p == '\n') { lineno++; p++; bol = true; } else if (p[0] == '\\' && p[1] == '\n') { p += 2; lineno++; bol = false; } else return; } } void parseargs::skiplwsp () { for (;;) { if (isspcnnl (*p)) p++; else if (p[0] == '\\' && p[1] == '\n') { p += 2; lineno++; } else return; } } str parseargs::getarg () { skiplwsp (); if (p >= lim || *p == '\n') return NULL; bool q = false; vec arg; for (;;) { if (*p == '\\') { if (p + 1 >= lim) { error ("invalid '\\' before end of file"); return NULL; } else if (p[1] == '\n') skiplwsp (); else { arg.push_back (p[1]); p += 2; } continue; } if (p >= lim) { if (q) error ("closing '\"' missing"); return str (arg.base (), arg.size ()); } if (*p == '\"') q = !q; else if (q || !isspc (*p)) arg.push_back (*p); else return str (arg.base (), arg.size ()); p++; } return NULL; // XXX - egcs bug } bool parseargs::getline (vec *args, int *linep) { args->setsize (0); skipblanks (); if (linep) *linep = lineno; while (str s = getarg ()) args->push_back (s); return args->size (); } void parseargs::error (str msg) { strbuf pref; if (filename) pref << filename << ":"; if (lineno) pref << lineno << ": "; else pref << " "; fatal << pref << msg << "\n"; } parseargs::parseargs (str file, int fd) : buf (errorbuf), lim (buf), p (buf), filename (file), lineno (0) { if (fd == -1 && (fd = open (file, O_RDONLY, 0)) < 0) { error (strbuf ("%m")); return; } // XXX - should fstat fd for initial size, to optimize for common case // when fd is for a regular file. size_t pos = 0; size_t size = 128; buf = static_cast (xmalloc (size)); for (;;) { ssize_t n = read (fd, buf + pos, size - pos); if (n < 0) { error (strbuf ("%m")); close (fd); return; } if (!n) { p = buf; lim = buf + pos; lineno = 1; close (fd); return; } pos += n; if (pos == size) size <<= 1; buf = static_cast (xrealloc (buf, size)); } } parseargs::~parseargs () { if (buf != errorbuf) xfree (buf); } void mytolower (char *dest, const char *src) { while (*src) *dest++ = tolower (*src++); *dest = 0; } str mytolower (const str &in) { const char *src = in.cstr (); char *dest = New char[in.len () + 1]; mytolower (dest, src); str r (dest); delete [] dest; return r; } bool conftab_str::convert (const vec &v, const str &l, bool *e) { if (dest) { if (!count_args (v, 2)) return false; else tmp_s = v[1]; } else if (scb) { tmp_s = v[1]; } else { tmp = v; } loc = l; errp = e; return true; } void conftab_str::set () { if (dest) { if (check) { if (dest->len ()) { warn << loc << ": " << name << ": variable already defined\n"; *errp = true; } else { *dest = tmp_s; } } else *dest = tmp_s; } else if (cnfcb) { (*cnfcb) (tmp, loc, errp); } else { (*scb) (tmp_s); } } bool conftab_bool::convert (const vec &v, const str &l, bool *e) { if (!count_args (v, 2)) return false; if (v[1] == "1") tmp = true; else if (v[1] == "0") tmp = false; else err = true; return (!err); } bool conftab::match (const vec &av, const str &cf, int ln, bool *err) { if (av.size () < 1) return false; str k = mytolower (av[0]); conftab_el *el = tab[k]; str loc = strbuf (cf) << ":" << ln; if (!el) return false; if (!el->convert (av, loc, err)) { warn << cf << ":" << ln << ": usage: " << el->name << " \n"; *err = true; } else if (!el->inbounds ()) { warn << cf << ":" << ln << ": " << el->name << " out of range\n"; *err = true; } else el->set (); return true; } avenger-0.8.5/libasync/rwfd.c0000644000175000017500000000572611221237220013010 00000000000000/* $Id$ */ /* * * Copyright (C) 2000 David Mazieres (dm@uun.org) * * 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 * */ #include "sysconf.h" #if !defined (HAVE_ACCRIGHTS) && !defined (HAVE_CMSGHDR) #error Do not know how to pass file descriptors #endif /* !HAVE_ACCRIGHTS && !HAVE_CMSGHDR */ ssize_t writevfd (int fd, const struct iovec *iov, int iovcnt, int wfd) { struct msghdr mh; #ifdef HAVE_CMSGHDR char cmhbuf[sizeof (struct cmsghdr) + sizeof (int)]; struct cmsghdr *const cmh = (struct cmsghdr *) cmhbuf; int *const fdp = (int *) (cmhbuf + sizeof (struct cmsghdr)); #else /* !HAVE_CMSGHDR */ int fdp[1]; #endif /* !HAVE_CMSGHDR */ *fdp = wfd; bzero (&mh, sizeof mh); mh.msg_iov = (struct iovec *) iov; mh.msg_iovlen = iovcnt; #ifdef HAVE_CMSGHDR mh.msg_control = (char *) cmh; mh.msg_controllen = cmh->cmsg_len = sizeof (cmhbuf) /* + sizeof (int) */; cmh->cmsg_level = SOL_SOCKET; cmh->cmsg_type = SCM_RIGHTS; #else /* !HAVE_CMSGHDR */ mh.msg_accrights = (char *) fdp; mh.msg_accrightslen = sizeof (fdp); #endif /* !HAVE_CMSGHDR */ return sendmsg (fd, &mh, 0); } ssize_t writefd (int fd, const void *buf, size_t len, int wfd) { struct iovec iov[1]; iov->iov_base = (void *) buf; iov->iov_len = len; return writevfd (fd, iov, 1, wfd); } ssize_t readvfd (int fd, const struct iovec *iov, int iovcnt, int *rfdp) { struct msghdr mh; #ifdef HAVE_CMSGHDR char cmhbuf[sizeof (struct cmsghdr) + sizeof (int)]; struct cmsghdr *const cmh = (struct cmsghdr *) cmhbuf; int *const fdp = (int *) (cmhbuf + sizeof (struct cmsghdr)); #else /* !HAVE_CMSGHDR */ int fdp[1]; #endif /* !HAVE_CMSGHDR */ int n; *fdp = -1; bzero (&mh, sizeof mh); mh.msg_iov = (struct iovec *) iov; mh.msg_iovlen = iovcnt; #ifdef HAVE_CMSGHDR mh.msg_control = (char *) cmh; mh.msg_controllen = cmh->cmsg_len = sizeof (cmhbuf) /* + sizeof (int) */; cmh->cmsg_level = SOL_SOCKET; cmh->cmsg_type = SCM_RIGHTS; #else /* !HAVE_CMSGHDR */ mh.msg_accrights = (char *) fdp; mh.msg_accrightslen = sizeof (fdp); #endif /* !HAVE_CMSGHDR */ n = recvmsg (fd, &mh, 0); *rfdp = *fdp; if (*fdp >= 0 && n == 0) { n = -1; errno = EAGAIN; } return n; } ssize_t readfd (int fd, void *buf, size_t len, int *rfdp) { struct iovec iov[1]; iov->iov_base = buf; iov->iov_len = len; return readvfd (fd, iov, 1, rfdp); } avenger-0.8.5/libasync/aios.C0000644000175000017500000001673611221237220012744 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #define __AIOS_IMPLEMENTATION #include "aios.h" #include "async.h" bssptr ain; bssptr aout; void aios::fail (int e) { ref hold = mkref (this); // Don't let this be freed under us eof = true; if (e) err = e; if (fd >= 0) { fdcb (fd, selread, NULL); if (rcb) mkrcb (NULL); if (fd >= 0 && err && err != ETIMEDOUT) { fdcb (fd, selwrite, NULL); outb.tosuio ()->clear (); } } } void aios::timeoutcatch () { time_t now = time (NULL); if (now < timeoutnext) { timeoutcb = timecb (timeoutnext, wrap (this, &aios::timeoutcatch)); return; } timeoutcb = NULL; if (timeoutval && (reading () || writing ())) { if (debugname) warnx << debugname << errpref << "Timeout\n"; fail (ETIMEDOUT); } } void aios::timeoutbump () { if (timeoutval && !eof) { timeoutnext = time (NULL) + timeoutval; if (!timeoutcb && (rcb || outb.tosuio ()->resid ())) timeoutcb = timecb (timeoutnext, wrap (this, &aios::timeoutcatch)); } } void aios::abort () { if (fd < 0) return; if (debugname) warnx << debugname << errpref << "EOF\n"; rcb = NULL; fdcb (fd, selread, NULL); fdcb (fd, selwrite, NULL); ::close (fd); fd = -1; eof = true; weof = true; err = EBADF; outb.tosuio ()->clear (); } int aios::doinput () { int n = ::readv (fd, const_cast (inb.iniov ()), inb.iniovcnt ()); if (n > 0) inb.addbytes (n); return n; } void aios::setincb () { if (fd >= 0) { if (rcb) fdcb (fd, selread, wrap (this, &aios::input)); else fdcb (fd, selread, NULL); //timeoutbump (); } } void aios::input () { if (rlock) return; rlock = true; ref hold = mkref (this); // Don't let this be freed under us int n = doinput (); if (n < 0 && errno != EAGAIN) { fail (errno); rlock = false; return; } else if (!n && !(this->*infn) ()) { fail (0); rlock = false; return; } while ((this->*infn) ()) ; rlock = false; setincb (); } bool aios::rline () { int lfp = inb.find ('\n'); if (lfp < 0) { if (!inb.space ()) { if (debugname) warnx << debugname << errpref << "Line too long\n"; fail (EFBIG); } return false; } mstr m (lfp + 1); inb.copyout (m, m.len ()); if (lfp > 1 && m.cstr ()[lfp - 1] == '\r') m.setlen (lfp - 1); else m.setlen (lfp); str s (m); if (debugname) warnx << debugname << rdpref << s << "\n"; mkrcb (s); return true; } bool aios::rany () { size_t bufsize = inb.size (); if (!bufsize) return false; mstr m (bufsize); inb.copyout (m, bufsize); mkrcb (m); return true; } void aios::setreadcb (bool (aios::*fn) (), rcb_t cb) { if (rcb) panic ("aios::setreadcb: read call made with read already pending\n"); if (eof || err) (*cb) (NULL, err); else { infn = fn; rcb = cb; timeoutbump (); input (); } } int aios::dooutput () { suio *out = outb.tosuio (); int res; if (fdsendq.empty ()) res = out->output (fd); else { int cnt = out->iovcnt (); if (cnt > UIO_MAXIOV) cnt = UIO_MAXIOV; res = writevfd (fd, out->iov (), cnt, fdsendq.front ()); if (res > 0) { out->rembytes (res); ::close (fdsendq.pop_front ()); } else if (res < 0 && errno == EAGAIN) res = 0; } if (weof && !outb.tosuio ()->resid ()) shutdown (fd, SHUT_WR); return res; } void aios::output () { ref hold = mkref (this); // Don't let this be freed under us int res = dooutput (); if (res < 0) { fail (errno); return; } if (res > 0) timeoutbump (); wblock = !res; setoutcb (); } void aios::setoutcb () { if (fd < 0) return; else if (err && err != ETIMEDOUT) { fdcb (fd, selwrite, NULL); outb.tosuio ()->clear (); } else if (outb.tosuio ()->resid ()) { if (!timeoutcb) timeoutbump (); fdcb (fd, selwrite, wrap (this, &aios::output)); } else fdcb (fd, selwrite, NULL); } void aios::schedwrite () { if (outb.tosuio ()->resid () < defrbufsize || wblock || err) setoutcb (); else output (); } void aios::dumpdebug () { if (debugiov < 0) return; bool prefprinted = false, crpending = false; strbuf text; for (const iovec *iov = outb.tosuio ()->iov () + debugiov, *const lim = outb.tosuio ()->iovlim (); iov < lim; iov++) { char *s = reinterpret_cast (iov->iov_base); char *e = s + iov->iov_len; char *p; for (; s < e && (p = reinterpret_cast (memchr (s, '\n', e - s))); s = p + 1) { if (crpending && p > s) text << "\r"; crpending = false; if (!prefprinted) text << debugname << wrpref; else prefprinted = false; if (p - 1 >= s && p[-1] == '\r') text.buf (s, p - s - 1) << "\n"; else text.buf (s, p - s + 1); } if (s < e) { if (e[-1] == '\r') { e--; crpending = true; } if (!prefprinted) text << debugname << wrpref; prefprinted = true; text.buf (s, e - s); } } if (prefprinted) text << "\n"; warnx << text; } aios::aios (int fd, size_t rbsz) : rlock (false), infn (&aios::rnone), wblock (false), timeoutval (0), timeoutcb (NULL), debugiov (-1), fd (fd), inb (rbsz), err (0), eof (false), weof (false), wrpref (" <== "), rdpref (" ==> "), errpref (" === ") { _make_async (fd); } aios::~aios () { if (fd >= 0) { if (debugname) warnx << debugname << errpref << "EOF\n"; fdcb (fd, selread, NULL); fdcb (fd, selwrite, NULL); ::close (fd); } if (timeoutcb) timecb_remove (timeoutcb); while (!fdsendq.empty ()) ::close (fdsendq.pop_front ()); } void aios::writev (const iovec *iov, int iovcnt) { assert (!weof); int n = 0; if (!outb.tosuio ()->resid ()) { n = ::writev (fd, const_cast (iov), iovcnt); if (n < 0) { if (errno != EAGAIN) { fail (errno); return; } n = 0; } if (n > 0) timeoutbump (); } outb.tosuio ()->copyv (iov, iovcnt, n); setoutcb (); } void aios::sendeof () { assert (!weof); weof = true; if (!outb.tosuio ()->resid ()) output (); } int aios::flush () { ptr hold; if (fd >= 0 && outb.tosuio ()->resid ()) { hold = mkref (this); // Don't let this be freed under us make_sync (fd); output (); _make_async (fd); } return err; } void aios::finalize () { if (globaldestruction) make_sync (fd); if (!outb.tosuio ()->resid () || fd < 0) delete this; else if (err) { // Make one last effort to flush buffer if (err == ETIMEDOUT) dooutput (); delete this; } else if (dooutput () < 0) delete this; } int aiosinit::count; void aiosinit::start () { ain = aios::alloc (0); aout = aios::alloc (1); } void aiosinit::stop () { ain = NULL; aout = NULL; } avenger-0.8.5/libasync/list.h0000644000175000017500000000576311221237220013027 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _LIST_H_INCLUDED_ #define _LIST_H_INCLUDED_ 1 template struct list_entry { T *next; T **pprev; }; template T::*field> class list { // forbid copying list (const list &); list &operator= (const list &); public: T *first; list () { first = NULL; } void insert_head (T *elm) { if (((elm->*field).next = first)) (first->*field).pprev = &(elm->*field).next; first = elm; (elm->*field).pprev = &first; } static T *remove (T *elm) { if ((elm->*field).next) ((elm->*field).next->*field).pprev = (elm->*field).pprev; *(elm->*field).pprev = (elm->*field).next; return elm; } static T *next (const T *elm) { return (elm->*field).next; } void traverse (typename callback::ref cb) const { T *p, *np; for (p = first; p; p = np) { np = (p->*field).next; (*cb) (p); } } void swap (list &b) { T *tp = first; if ((first = b.first)) (first->*field).pprev = &first; if ((b.first = tp)) (tp->*field).pprev = &b.first; } }; #if 0 template inline void list_remove (T *elm, list_entry T::*field) { list::remove (elm); } #endif template struct tailq_entry { T *next; T **pprev; }; template T::*field> struct tailq { T *first; T **plast; tailq () {first = NULL; plast = &first;} void insert_head (T *elm) { if (((elm->*field).next = first)) (first->*field).pprev = &(elm->*field).next; else plast = &(elm->*field).next; first = elm; (elm->*field).pprev = &first; } void insert_tail (T *elm) { (elm->*field).next = NULL; (elm->*field).pprev = plast; *plast = elm; plast = &(elm->*field).next; } T *remove (T *elm) { if ((elm->*field).next) ((elm->*field).next->*field).pprev = (elm->*field).pprev; else plast = (elm->*field).pprev; *(elm->*field).pprev = (elm->*field).next; return elm; } static T *next (T *elm) { return (elm->*field).next; } void traverse (typename callback::ref cb) const { T *p, *np; for (p = first; p; p = np) { np = (p->*field).next; (*cb) (p); } } }; #endif /* !_LIST_H_INCLUDED_ */ avenger-0.8.5/libasync/amisc.h0000644000175000017500000001470712260422177013161 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_AMISC_H_ #define _ASYNC_AMISC_H_ 1 #include "sysconf.h" #include "err.h" #include "callback.h" #include "serial.h" /* getopt declarations */ extern char *optarg; extern int optind; /* Common callback types */ typedef callback::ref cbv; typedef callback::ref cbi; typedef callback::ref cbs; typedef callback::ref cbb; extern cbs cbs_null; extern cbb cbb_null; extern cbv cbv_null; extern cbi cbi_null; /* arandom.c */ extern "C" { extern u_int32_t (*arandom_fn) (); u_int32_t arandom (); } /* straux.C */ char *mempbrk (char *, const char *, int); char *xstrsep (char **, const char *); char *strnnsep (char **, const char *); /* socket.C */ extern in_addr inet_bindaddr; int inetsocket (int, u_int16_t = 0, u_int32_t = INADDR_ANY); int inetsocket_resvport (int, u_int32_t = INADDR_ANY); int unixsocket (const char *); int unixsocket_connect (const char *); bool isunixsocket (int); void close_on_exec (int, bool = true); int _make_async (int); void make_async (int); void make_sync (int); void tcp_nodelay (int); void tcp_abort (int); bool addreq (const sockaddr *, const sockaddr *, socklen_t); /* sigio.C */ int sigio_set (int fd); int sigio_clear (int fd); /* passfd.c */ #include "rwfd.h" /* myname.C */ str myname (); str mydomain (); /* myaddrs.C */ bool myipaddrs (vec *res); /* fdwait.C */ enum selop { selread = 0, selwrite = 1 }; int fdwait (int fd, bool r, bool w, timeval *tvp); int fdwait (int fd, selop op, timeval *tvp = NULL); /* spawn.C */ extern str execdir; #ifdef MAINTAINER extern str builddir; // For running programs in place extern str buildtmpdir; // For creating files (e.g. prog.pid) #endif /* MAINTAINER */ pid_t afork (); str fix_exec_path (str path, str dir = NULL); str find_program (const char *program); str find_program_plus_libsfs (const char *program); pid_t spawn (const char *, char *const *, int in = 0, int out = 1, int err = 2, cbv::ptr postforkcb = NULL, char *const *env = NULL); inline pid_t spawn (const char *path, const char *const *av, int in = 0, int out = 1, int err = 2, cbv::ptr postforkcb = NULL, char *const *env = NULL) { return spawn (path, const_cast (av), in, out, err, postforkcb, env); } pid_t aspawn (const char *, char *const *, int in = 0, int out = 1, int err = 2, cbv::ptr postforkcb = NULL, char *const *env = NULL); inline pid_t aspawn (const char *path, const char *const *av, int in = 0, int out = 1, int err = 2, cbv::ptr postforkcb = NULL, char *const *env = NULL) { return aspawn (path, const_cast (av), in, out, err, postforkcb, env); } /* lockfile.C */ bool stat_unchanged (const struct stat *sb1, const struct stat *sb2); class lockfile { protected: bool islocked; int fd; ~lockfile (); bool openit (); void closeit (); bool fdok (); public: const str path; lockfile (const str &p) : islocked (false), fd (-1), path (p) {} bool locked () const { return islocked; } int getfd () const { return fd; } bool acquire (bool wait = false); void release (); bool ok () { return islocked && fdok (); } static ptr alloc (const str &path, bool wait = false); }; /* daemonize.C */ extern str syslog_priority; void daemonize (str tag = NULL); void start_logger (str tag = NULL); int start_logger (const str &pri, const str &tag, const str &line, const str &logfile, int flags, mode_t mode); /* Random usefull operators */ #include "keyfunc.h" inline in_addr inaddr_cast (const void *p) { in_addr a; memcpy (&a, p, sizeof (a)); return a; } inline bool operator== (const in_addr &a, const in_addr &b) { return a.s_addr == b.s_addr; } inline bool operator!= (const in_addr &a, const in_addr &b) { return a.s_addr != b.s_addr; } template<> struct hashfn { hashfn () {} hash_t operator() (const in_addr a) const { return a.s_addr; } }; inline bool operator== (const sockaddr_in &a, const sockaddr_in &b) { return a.sin_port == b.sin_port && a.sin_addr.s_addr == b.sin_addr.s_addr; } inline bool operator!= (const sockaddr_in &a, const sockaddr_in &b) { return a.sin_port != b.sin_port || a.sin_addr.s_addr != b.sin_addr.s_addr; } template<> struct hashfn { hashfn () {} hash_t operator() (const sockaddr_in &a) const { return ntohs (a.sin_port) << 16 ^ htonl (a.sin_addr.s_addr); } }; inline bool operator== (const timespec &a, const timespec &b) { return a.tv_nsec == b.tv_nsec && a.tv_sec == b.tv_sec; } inline bool operator!= (const timespec &a, const timespec &b) { return a.tv_nsec != b.tv_nsec || a.tv_sec != b.tv_sec; } inline int tscmp (const timespec &a, const timespec &b) { if (a.tv_sec < b.tv_sec) return -1; if (b.tv_sec < a.tv_sec) return 1; if (a.tv_nsec < b.tv_nsec) return -1; return b.tv_nsec < a.tv_nsec; }; inline bool operator< (const timespec &a, const timespec &b) { return tscmp (a, b) < 0; } inline bool operator<= (const timespec &a, const timespec &b) { return tscmp (a, b) <= 0; } inline bool operator> (const timespec &a, const timespec &b) { return tscmp (a, b) > 0; } inline bool operator>= (const timespec &a, const timespec &b) { return tscmp (a, b) >= 0; } inline timespec operator+ (const timespec &a, const timespec &b) { timespec ts; ts.tv_sec = a.tv_sec + b.tv_sec; if ((ts.tv_nsec = a.tv_nsec + b.tv_nsec) > 1000000000) { ts.tv_nsec -= 1000000000; ++ts.tv_sec; } return ts; } inline timespec operator- (const timespec &a, const timespec &b) { timespec ts; ts.tv_sec = a.tv_sec - b.tv_sec; if (a.tv_nsec > b.tv_nsec) ts.tv_nsec = a.tv_nsec - b.tv_nsec; else { ts.tv_nsec = a.tv_nsec + 1000000000 - b.tv_nsec; --ts.tv_sec; } return ts; } #endif /* !_ASYNC_AMISC_H_ */ avenger-0.8.5/libasync/itree.h0000644000175000000120000001444112077217760013164 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ITREE_H_ #define _ITREE_H_ 1 #include "callback.h" #include "keyfunc.h" struct __opaquecontainer; #define oc __opaquecontainer_pointer typedef __opaquecontainer *oc; enum itree_color {INVALID, BLACK, RED}; void itree_insert (oc *, oc, const int, int (*) (void *, oc, oc), void *); void itree_delete (oc *, oc, const int); oc itree_successor (oc, const int); oc itree_predecessor (oc, const int); void __itree_check(oc *, const int, int (*) (void *, oc, oc), void *); #ifdef ITREE_DEBUG #define itree_check(r, os, cmpfn) __itree_check(r, os, cmpfn) #else /* !ITREE_DEBUG */ #define itree_check(r, os, cmpfn) #endif /* !ITREE_DEBUG */ struct __itree_entry_private { oc rbe_up; oc rbe_left; oc rbe_right; enum itree_color rbe_color; }; template #ifndef NO_TEMPLATE_FRIENDS class #else /* NO_TEMPLATE_FRIENDS */ struct #endif /* NO_TEMPLATE_FRIENDS */ itree_entry { __itree_entry_private p; #ifndef NO_TEMPLATE_FRIENDS /* Let's get friendly with the implementation... */ template U::*field, class C> friend class itree_core; #endif /* NO_TEMPLATE_FRIENDS */ public: T *up () const { return (T *) p.rbe_up; } T *left () const { return (T *) p.rbe_left; } T *right () const { return (T *) p.rbe_right; } }; template T::*field, class C = compare > class itree_core { protected: oc rb_root; const C cmp; static int scmp (void *t, oc a, oc b) { return (((itree_core *) t)->cmp) (*(T *) a, *(T *) b); } /* No copying */ itree_core (const itree_core &); itree_core &operator = (const itree_core &); #define eos ((ptrdiff_t) &(((T *) 0)->*field).p) #define cmpfn scmp, (void *) this void _deleteall_correct (T *n) { if (n) { _deleteall_correct (left (n)); _deleteall_correct (right (n)); delete n; } } public: itree_core () { clear (); } itree_core (const C &c) : cmp (c) { clear (); } // MK 7/6/05: deleteall() is fast but broken; accesses freed memory; // deleteall_correct () is slow but should be safer. // DM: deleteall () possibly fixed void deleteall_correct () { _deleteall_correct (root ()); clear (); } static T *min_postorder (T *n) { T *nn; if (n) while ((nn = left (n)) || (nn = right (n))) n = nn; return n; } static T *next_postorder (const T *n) { T *nn = up (n), *nnr; if (nn && (nnr = right (nn)) && n != nnr) return min_postorder (nnr); return nn; } void deleteall () { T *n, *nn; for (n = min_postorder (root ()); n; n = nn) { nn = next_postorder (n); delete n; } clear (); } void clear () {rb_root = NULL;} T *root () const { return (T *) rb_root; } static T *up (const T *n) { return (n->*field).up (); } static T *left (const T *n) { return (n->*field).left (); } static T *right (const T *n) { return (n->*field).right (); } T *first () const { T *n, *nn; for (n = root (); n && (nn = left (n)); n = nn) ; return n; } static T *next (const T *n) { return (T *) itree_successor ((oc) n, eos); } static T *prev (const T *n) { return (T *) itree_predecessor ((oc) n, eos); } void insert (T *n) { itree_insert (&rb_root, (oc) n, eos, cmpfn); itree_check (&rb_root, eos, cmpfn); } void remove (T *n) { itree_delete (&rb_root, (oc) n, eos); itree_check (&rb_root, eos, cmpfn); } T *search (typename callback::ref cb) const { T *ret = NULL; T *n = root (); while (n) { int srchres = (*cb) (n); if (srchres < 0) n = left (n); else if (srchres > 0) n = right (n); else { /* In case there are duplicate keys, keep looking for the first one */ ret = n; n = left (n); } } return ret; } // XXX - template search to work around egcs 1.2 bug template T *search (int (*cb) (const A1 *, const A2 *, const T*), const A1 *a1, const A2 *a2) const { T *ret = NULL; T *n = root (); while (n) { int srchres = (*cb) (a1, a2, n); if (srchres < 0) n = left (n); else if (srchres > 0) n = right (n); else { /* In case there are duplicate keys, keep looking for the first one */ ret = n; n = left (n); } } return ret; } void traverse (typename callback::ref cb) { T *n, *nn; for (n = first (); n; n = nn) { nn = next (n); (*cb) (n); } } void traverse (void (T::*fn) ()) { T *n, *nn; for (n = first (); n; n = nn) { nn = next (n); (n->*fn) (); } } #undef eos #undef cmpfn }; #undef oc template V::*field, class C = compare > class itree : public itree_core > { typedef keyfunc_2 cmp_t; typedef itree_core core_t; const C kcmp; #if 0 template int kvcmp (const T *k, const V *v) { return kcmp (*k, v->*key); } #else int kvcmp (const K *k, const V *v) { return kcmp (*k, v->*key); } #endif static int skvcmp (const C *c, const K *k, const V *v) { return (*c) (*k, v->*key); } public: itree () {} itree (const C &c) : core_t (cmp_t (c)), kcmp (c) {} #if 0 template V *operator[] (const T &k) { int (itree::*fn) (const T *, const V *) = &kvcmp; return this->search (wrap (this, fn, &k)); } #else V *operator[] (const K &k) { // return search (wrap (this, &kvcmp, &k)); return this->search (skvcmp, &kcmp, &k); } #endif }; #endif /* !_ITREE_H_ */ avenger-0.8.5/libasync/parseopt.h0000644000175000017500000001125011221237220013675 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_PARSEOPT_ #define _ASYNC_PARSEOPT_ 1 #include "vec.h" #include "str.h" #include "ihash.h" #include "amisc.h" class parseargs { static char *errorbuf; char *buf; const char *lim; const char *p; void skipblanks (); void skiplwsp (); str getarg (); protected: str filename; int lineno; virtual void error (str); public: parseargs (str file, int fd = -1); virtual ~parseargs (); bool getline (vec *args, int *linep = NULL); }; int64_t strtoi64 (const char *nptr, char **endptr = NULL, int base = 0); template bool convertint (const char *cp, T *resp) { if (!*cp) return false; char *end; T res = strtoi64 (cp, &end, 0); if (*end) return false; *resp = res; return true; } void mytolower (char *dest, const char *src); str mytolower (const str &in); class conftab_el { public: conftab_el (const str &n) : name (n), lcname (mytolower (n)) {} virtual ~conftab_el () {} virtual bool convert (const vec &v, const str &loc, bool *e) = 0; virtual bool inbounds () = 0; virtual void set () = 0; inline bool count_args (const vec &v, u_int l) { return (v.size () == l || (v.size () > l && v[l][0] == '#')); } const str name; const str lcname; ihash_entry lnk; }; class conftab_ignore : public conftab_el { public: conftab_ignore (const str &n) : conftab_el (n) {} bool convert (const vec &v, const str &loc, bool *e) { return true; } bool inbounds () { return true; } void set () {} }; typedef callback, str, bool *>::ref confcb; class conftab_str : public conftab_el { public: conftab_str (const str &n, str *d, bool c = false) : conftab_el (n), dest (d), cnfcb (NULL), scb (NULL), check (c) {} conftab_str (const str &n, confcb c) : conftab_el (n), dest (NULL), cnfcb (c), scb (NULL), check (false) {} conftab_str (cbs c, const str &n) // XXX: reverse order to disambiguate : conftab_el (n), dest (NULL), cnfcb (NULL), scb (c), check (false) {} bool convert (const vec &v, const str &l, bool *e); bool inbounds () { return true; } void set (); private: str *const dest; confcb::ptr cnfcb; cbs::ptr scb; const bool check; vec tmp; str tmp_s; str loc; bool *errp; }; template class conftab_int : public conftab_el { public: conftab_int (const str &n, T *d, T l, T u) : conftab_el (n), dest (d), lb (l), ub (u) {} bool convert (const vec &v, const str &cf, bool *e) { return (count_args (v, 2) && convertint (v[1], &tmp)); } bool inbounds () { return (tmp >= lb && tmp <= ub); } void set () { *dest = tmp; } private: T *const dest; const T lb; const T ub; T tmp; }; class conftab_bool : public conftab_el { public: conftab_bool (const str &n, bool *b) : conftab_el (n), dest (b), err (false) {} bool convert (const vec &v, const str &cf, bool *e); bool inbounds () { return !(err); } void set () { *dest = tmp; } private: bool tmp; bool *dest; bool err; }; class conftab { public: conftab () {} template conftab &add (const str &nm, P *dp, D lb, D ub) { tab.insert (New conftab_int

(nm, dp, lb, ub)); return *this; } template conftab &add (const str &nm, A a) { tab.insert (New conftab_str (nm, a)); return *this; } conftab &ads (const str &nm, cbs c) // XXX: cannot overload { tab.insert (New conftab_str (c, nm)); return *this; } conftab &add (const str &nm, str *s, bool b) { tab.insert (New conftab_str (nm, s, b)); return *this; } conftab &add (const str &nm, bool *b) { tab.insert (New conftab_bool (nm, b)); return *this; } conftab &ignore (const str &m) { tab.insert (New conftab_ignore (m)); return *this; } ~conftab () { tab.deleteall (); } bool match (const vec &s, const str &cf, int ln, bool *err); private: ihash tab; }; #endif /* !_ASYNC_PARSEOPT_ */ avenger-0.8.5/libasync/autoconf.h0000644000175000017500000000000011221235216013650 00000000000000avenger-0.8.5/libasync/pcre.h0000644000175000017500000001557611221235746013023 00000000000000/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* Copyright (c) 1997-2003 University of Cambridge */ #ifndef _PCRE_H #define _PCRE_H /* The file pcre.h is build by "configure". Do not edit it; instead make changes to pcre.in. */ #define PCRE_MAJOR 4 #define PCRE_MINOR 5 #define PCRE_DATE 01-December-2003 /* Win32 uses DLL by default */ #ifdef _WIN32 # ifdef PCRE_DEFINITION # ifdef DLL_EXPORT # define PCRE_DATA_SCOPE __declspec(dllexport) # endif # else # ifndef PCRE_STATIC # define PCRE_DATA_SCOPE extern __declspec(dllimport) # endif # endif #endif #ifndef PCRE_DATA_SCOPE # define PCRE_DATA_SCOPE extern #endif /* Have to include stdlib.h in order to ensure that size_t is defined; it is needed here for malloc. */ #include /* Allow for C++ users */ #ifdef __cplusplus extern "C" { #endif /* Options */ #define PCRE_CASELESS 0x0001 #define PCRE_MULTILINE 0x0002 #define PCRE_DOTALL 0x0004 #define PCRE_EXTENDED 0x0008 #define PCRE_ANCHORED 0x0010 #define PCRE_DOLLAR_ENDONLY 0x0020 #define PCRE_EXTRA 0x0040 #define PCRE_NOTBOL 0x0080 #define PCRE_NOTEOL 0x0100 #define PCRE_UNGREEDY 0x0200 #define PCRE_NOTEMPTY 0x0400 #define PCRE_UTF8 0x0800 #define PCRE_NO_AUTO_CAPTURE 0x1000 #define PCRE_NO_UTF8_CHECK 0x2000 /* Exec-time and get/set-time error codes */ #define PCRE_ERROR_NOMATCH (-1) #define PCRE_ERROR_NULL (-2) #define PCRE_ERROR_BADOPTION (-3) #define PCRE_ERROR_BADMAGIC (-4) #define PCRE_ERROR_UNKNOWN_NODE (-5) #define PCRE_ERROR_NOMEMORY (-6) #define PCRE_ERROR_NOSUBSTRING (-7) #define PCRE_ERROR_MATCHLIMIT (-8) #define PCRE_ERROR_CALLOUT (-9) /* Never used by PCRE itself */ #define PCRE_ERROR_BADUTF8 (-10) #define PCRE_ERROR_BADUTF8_OFFSET (-11) /* Request types for pcre_fullinfo() */ #define PCRE_INFO_OPTIONS 0 #define PCRE_INFO_SIZE 1 #define PCRE_INFO_CAPTURECOUNT 2 #define PCRE_INFO_BACKREFMAX 3 #define PCRE_INFO_FIRSTBYTE 4 #define PCRE_INFO_FIRSTCHAR 4 /* For backwards compatibility */ #define PCRE_INFO_FIRSTTABLE 5 #define PCRE_INFO_LASTLITERAL 6 #define PCRE_INFO_NAMEENTRYSIZE 7 #define PCRE_INFO_NAMECOUNT 8 #define PCRE_INFO_NAMETABLE 9 #define PCRE_INFO_STUDYSIZE 10 /* Request types for pcre_config() */ #define PCRE_CONFIG_UTF8 0 #define PCRE_CONFIG_NEWLINE 1 #define PCRE_CONFIG_LINK_SIZE 2 #define PCRE_CONFIG_POSIX_MALLOC_THRESHOLD 3 #define PCRE_CONFIG_MATCH_LIMIT 4 #define PCRE_CONFIG_STACKRECURSE 5 /* Bit flags for the pcre_extra structure */ #define PCRE_EXTRA_STUDY_DATA 0x0001 #define PCRE_EXTRA_MATCH_LIMIT 0x0002 #define PCRE_EXTRA_CALLOUT_DATA 0x0004 /* Types */ struct real_pcre; /* declaration; the definition is private */ typedef struct real_pcre pcre; /* The structure for passing additional data to pcre_exec(). This is defined in such as way as to be extensible. */ typedef struct pcre_extra { unsigned long int flags; /* Bits for which fields are set */ void *study_data; /* Opaque data from pcre_study() */ unsigned long int match_limit; /* Maximum number of calls to match() */ void *callout_data; /* Data passed back in callouts */ } pcre_extra; /* The structure for passing out data via the pcre_callout_function. We use a structure so that new fields can be added on the end in future versions, without changing the API of the function, thereby allowing old clients to work without modification. */ typedef struct pcre_callout_block { int version; /* Identifies version of block */ /* ------------------------ Version 0 ------------------------------- */ int callout_number; /* Number compiled into pattern */ int *offset_vector; /* The offset vector */ const char *subject; /* The subject being matched */ int subject_length; /* The length of the subject */ int start_match; /* Offset to start of this match attempt */ int current_position; /* Where we currently are */ int capture_top; /* Max current capture */ int capture_last; /* Most recently closed capture */ void *callout_data; /* Data passed in with the call */ /* ------------------------------------------------------------------ */ } pcre_callout_block; /* Indirection for store get and free functions. These can be set to alternative malloc/free functions if required. Special ones are used in the non-recursive case for "frames". There is also an optional callout function that is triggered by the (?) regex item. Some magic is required for Win32 DLL; it is null on other OS. For Virtual Pascal, these have to be different again. */ #ifndef VPCOMPAT PCRE_DATA_SCOPE void *(*pcre_malloc)(size_t); PCRE_DATA_SCOPE void (*pcre_free)(void *); PCRE_DATA_SCOPE void *(*pcre_stack_malloc)(size_t); PCRE_DATA_SCOPE void (*pcre_stack_free)(void *); PCRE_DATA_SCOPE int (*pcre_callout)(pcre_callout_block *); #else /* VPCOMPAT */ extern void *pcre_malloc(size_t); extern void pcre_free(void *); extern void *pcre_stack_malloc(size_t); extern void pcre_stack_free(void *); extern int pcre_callout(pcre_callout_block *); #endif /* VPCOMPAT */ /* Exported PCRE functions */ extern pcre *pcre_compile(const char *, int, const char **, int *, const unsigned char *); extern int pcre_config(int, void *); extern int pcre_copy_named_substring(const pcre *, const char *, int *, int, const char *, char *, int); extern int pcre_copy_substring(const char *, int *, int, int, char *, int); extern int pcre_exec(const pcre *, const pcre_extra *, const char *, int, int, int, int *, int); extern void pcre_free_substring(const char *); extern void pcre_free_substring_list(const char **); extern int pcre_fullinfo(const pcre *, const pcre_extra *, int, void *); extern int pcre_get_named_substring(const pcre *, const char *, int *, int, const char *, const char **); extern int pcre_get_stringnumber(const pcre *, const char *); extern int pcre_get_substring(const char *, int *, int, int, const char **); extern int pcre_get_substring_list(const char *, int *, int, const char ***); extern int pcre_info(const pcre *, int *, int *); extern const unsigned char *pcre_maketables(void); extern pcre_extra *pcre_study(const pcre *, int, const char **); extern const char *pcre_version(void); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* End of pcre.h */ avenger-0.8.5/libasync/pcre.c0000644000175000017500000076311711221235745013016 00000000000000/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* This is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. See the file Tech.Notes for some information on the internals. Written by: Philip Hazel Copyright (c) 1997-2003 University of Cambridge ----------------------------------------------------------------------------- Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software 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. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), then the terms of that licence shall supersede any condition above with which it is incompatible. ----------------------------------------------------------------------------- */ /* Define DEBUG to get debugging output on stdout. */ /* #define DEBUG */ /* Use a macro for debugging printing, 'cause that eliminates the use of #ifdef inline, and there are *still* stupid compilers about that don't like indented pre-processor statements. I suppose it's only been 10 years... */ #ifdef DEBUG #define DPRINTF(p) printf p #else #define DPRINTF(p) /*nothing*/ #endif /* Include the internals header, which itself includes "config.h", the Standard C headers, and the external pcre header. */ #include "internal.h" /* Allow compilation as C++ source code, should anybody want to do that. */ #ifdef __cplusplus #define class pcre_class #endif /* Maximum number of items on the nested bracket stacks at compile time. This applies to the nesting of all kinds of parentheses. It does not limit un-nested, non-capturing parentheses. This number can be made bigger if necessary - it is used to dimension one int and one unsigned char vector at compile time. */ #define BRASTACK_SIZE 200 /* Maximum number of ints of offset to save on the stack for recursive calls. If the offset vector is bigger, malloc is used. This should be a multiple of 3, because the offset vector is always a multiple of 3 long. */ #define REC_STACK_SAVE_MAX 30 /* The number of bytes in a literal character string above which we can't add any more is set at 250 in order to allow for UTF-8 characters. (In theory it could be 255 when UTF-8 support is excluded, but that means that some of the test output would be different, which just complicates things.) */ #define MAXLIT 250 /* The maximum remaining length of subject we are prepared to search for a req_byte match. */ #define REQ_BYTE_MAX 1000 /* Table of sizes for the fixed-length opcodes. It's defined in a macro so that the definition is next to the definition of the opcodes in internal.h. */ static const uschar OP_lengths[] = { OP_LENGTHS }; /* Min and max values for the common repeats; for the maxima, 0 => infinity */ static const char rep_min[] = { 0, 0, 1, 1, 0, 0 }; static const char rep_max[] = { 0, 0, 0, 0, 1, 1 }; /* Table for handling escaped characters in the range '0'-'z'. Positive returns are simple data values; negative values are for special things like \d and so on. Zero means further processing is needed (for things like \x), or the escape is invalid. */ #if !EBCDIC /* This is the "normal" table for ASCII systems */ static const short int escapes[] = { 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 7 */ 0, 0, ':', ';', '<', '=', '>', '?', /* 8 - ? */ '@', -ESC_A, -ESC_B, -ESC_C, -ESC_D, -ESC_E, 0, -ESC_G, /* @ - G */ 0, 0, 0, 0, 0, 0, 0, 0, /* H - O */ 0, -ESC_Q, 0, -ESC_S, 0, 0, 0, -ESC_W, /* P - W */ 0, 0, -ESC_Z, '[', '\\', ']', '^', '_', /* X - _ */ '`', 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, /* ` - g */ 0, 0, 0, 0, 0, 0, ESC_n, 0, /* h - o */ 0, 0, ESC_r, -ESC_s, ESC_tee, 0, 0, -ESC_w, /* p - w */ 0, 0, -ESC_z /* x - z */ }; #else /* This is the "abnormal" table for EBCDIC systems */ static const short int escapes[] = { /* 48 */ 0, 0, 0, '.', '<', '(', '+', '|', /* 50 */ '&', 0, 0, 0, 0, 0, 0, 0, /* 58 */ 0, 0, '!', '$', '*', ')', ';', '~', /* 60 */ '-', '/', 0, 0, 0, 0, 0, 0, /* 68 */ 0, 0, '|', ',', '%', '_', '>', '?', /* 70 */ 0, 0, 0, 0, 0, 0, 0, 0, /* 78 */ 0, '`', ':', '#', '@', '\'', '=', '"', /* 80 */ 0, 7, -ESC_b, 0, -ESC_d, ESC_e, ESC_f, 0, /* 88 */ 0, 0, 0, '{', 0, 0, 0, 0, /* 90 */ 0, 0, 0, 'l', 0, ESC_n, 0, 0, /* 98 */ 0, ESC_r, 0, '}', 0, 0, 0, 0, /* A0 */ 0, '~', -ESC_s, ESC_tee, 0, 0, -ESC_w, 0, /* A8 */ 0,-ESC_z, 0, 0, 0, '[', 0, 0, /* B0 */ 0, 0, 0, 0, 0, 0, 0, 0, /* B8 */ 0, 0, 0, 0, 0, ']', '=', '-', /* C0 */ '{',-ESC_A, -ESC_B, -ESC_C, -ESC_D,-ESC_E, 0, -ESC_G, /* C8 */ 0, 0, 0, 0, 0, 0, 0, 0, /* D0 */ '}', 0, 0, 0, 0, 0, 0, 0, /* D8 */-ESC_Q, 0, 0, 0, 0, 0, 0, 0, /* E0 */ '\\', 0, -ESC_S, 0, 0, 0, -ESC_W, 0, /* E8 */ 0,-ESC_Z, 0, 0, 0, 0, 0, 0, /* F0 */ 0, 0, 0, 0, 0, 0, 0, 0, /* F8 */ 0, 0, 0, 0, 0, 0, 0, 0 }; #endif /* Tables of names of POSIX character classes and their lengths. The list is terminated by a zero length entry. The first three must be alpha, upper, lower, as this is assumed for handling case independence. */ static const char *const posix_names[] = { "alpha", "lower", "upper", "alnum", "ascii", "blank", "cntrl", "digit", "graph", "print", "punct", "space", "word", "xdigit" }; static const uschar posix_name_lengths[] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 6, 0 }; /* Table of class bit maps for each POSIX class; up to three may be combined to form the class. The table for [:blank:] is dynamically modified to remove the vertical space characters. */ static const int posix_class_maps[] = { cbit_lower, cbit_upper, -1, /* alpha */ cbit_lower, -1, -1, /* lower */ cbit_upper, -1, -1, /* upper */ cbit_digit, cbit_lower, cbit_upper, /* alnum */ cbit_print, cbit_cntrl, -1, /* ascii */ cbit_space, -1, -1, /* blank - a GNU extension */ cbit_cntrl, -1, -1, /* cntrl */ cbit_digit, -1, -1, /* digit */ cbit_graph, -1, -1, /* graph */ cbit_print, -1, -1, /* print */ cbit_punct, -1, -1, /* punct */ cbit_space, -1, -1, /* space */ cbit_word, -1, -1, /* word - a Perl extension */ cbit_xdigit,-1, -1 /* xdigit */ }; /* Table to identify digits and hex digits. This is used when compiling patterns. Note that the tables in chartables are dependent on the locale, and may mark arbitrary characters as digits - but the PCRE compiling code expects to handle only 0-9, a-z, and A-Z as digits when compiling. That is why we have a private table here. It costs 256 bytes, but it is a lot faster than doing character value tests (at least in some simple cases I timed), and in some applications one wants PCRE to compile efficiently as well as match efficiently. For convenience, we use the same bit definitions as in chartables: 0x04 decimal digit 0x08 hexadecimal digit Then we can use ctype_digit and ctype_xdigit in the code. */ #if !EBCDIC /* This is the "normal" case, for ASCII systems */ static const unsigned char digitab[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - ' */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ( - / */ 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 */ 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00, /* 8 - ? */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* @ - G */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H - O */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* P - W */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* X - _ */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* ` - g */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h - o */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* p - w */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* x -127 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 128-135 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 136-143 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144-151 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 152-159 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160-167 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 168-175 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 176-183 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 192-199 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 200-207 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 208-215 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 216-223 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 224-231 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 232-239 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 240-247 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};/* 248-255 */ #else /* This is the "abnormal" case, for EBCDIC systems */ static const unsigned char digitab[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 0- 7 0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 16- 23 10 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 32- 39 20 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 30 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 40 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 72- | */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 50 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 88- ¬ */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 60 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 104- ? */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 70 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* 128- g 80 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 144- p 90 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 160- x A0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 B0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x00, /* { - G C0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* } - P D0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* \ - X E0 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ 0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c,0x0c, /* 0 - 7 F0 */ 0x0c,0x0c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ static const unsigned char ebcdic_chartab[] = { /* chartable partial dup */ 0x80,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 0- 7 */ 0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x00, /* 8- 15 */ 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 16- 23 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 24- 31 */ 0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, /* 32- 39 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 40- 47 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 48- 55 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 56- 63 */ 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - 71 */ 0x00,0x00,0x00,0x80,0x00,0x80,0x80,0x80, /* 72- | */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* & - 87 */ 0x00,0x00,0x00,0x80,0x80,0x80,0x00,0x00, /* 88- ¬ */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* - -103 */ 0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x80, /* 104- ? */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 112-119 */ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* 120- " */ 0x00,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* 128- g */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* h -143 */ 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* 144- p */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* q -159 */ 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* 160- x */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* y -175 */ 0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00, /* ^ -183 */ 0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00, /* 184-191 */ 0x80,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x12, /* { - G */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* H -207 */ 0x00,0x12,0x12,0x12,0x12,0x12,0x12,0x12, /* } - P */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Q -223 */ 0x00,0x00,0x12,0x12,0x12,0x12,0x12,0x12, /* \ - X */ 0x12,0x12,0x00,0x00,0x00,0x00,0x00,0x00, /* Y -239 */ 0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c,0x1c, /* 0 - 7 */ 0x1c,0x1c,0x00,0x00,0x00,0x00,0x00,0x00};/* 8 -255 */ #endif /* Definition to allow mutual recursion */ static BOOL compile_regex(int, int, int *, uschar **, const uschar **, const char **, BOOL, int, int *, int *, branch_chain *, compile_data *); /* Structure for building a chain of data that actually lives on the stack, for holding the values of the subject pointer at the start of each subpattern, so as to detect when an empty string has been matched by a subpattern - to break infinite loops. When NO_RECURSE is set, these blocks are on the heap, not on the stack. */ typedef struct eptrblock { struct eptrblock *epb_prev; const uschar *epb_saved_eptr; } eptrblock; /* Flag bits for the match() function */ #define match_condassert 0x01 /* Called to check a condition assertion */ #define match_isgroup 0x02 /* Set if start of bracketed group */ /* Non-error returns from the match() function. Error returns are externally defined PCRE_ERROR_xxx codes, which are all negative. */ #define MATCH_MATCH 1 #define MATCH_NOMATCH 0 /************************************************* * Global variables * *************************************************/ /* PCRE is thread-clean and doesn't use any global variables in the normal sense. However, it calls memory allocation and free functions via the four indirections below, and it can optionally do callouts. These values can be changed by the caller, but are shared between all threads. However, when compiling for Virtual Pascal, things are done differently (see pcre.in). */ #ifndef VPCOMPAT #ifdef __cplusplus extern "C" void *(*pcre_malloc)(size_t) = malloc; extern "C" void (*pcre_free)(void *) = free; extern "C" void *(*pcre_stack_malloc)(size_t) = malloc; extern "C" void (*pcre_stack_free)(void *) = free; extern "C" int (*pcre_callout)(pcre_callout_block *) = NULL; #else void *(*pcre_malloc)(size_t) = malloc; void (*pcre_free)(void *) = free; void *(*pcre_stack_malloc)(size_t) = malloc; void (*pcre_stack_free)(void *) = free; int (*pcre_callout)(pcre_callout_block *) = NULL; #endif #endif /************************************************* * Macros and tables for character handling * *************************************************/ /* When UTF-8 encoding is being used, a character is no longer just a single byte. The macros for character handling generate simple sequences when used in byte-mode, and more complicated ones for UTF-8 characters. */ #ifndef SUPPORT_UTF8 #define GETCHAR(c, eptr) c = *eptr; #define GETCHARINC(c, eptr) c = *eptr++; #define GETCHARINCTEST(c, eptr) c = *eptr++; #define GETCHARLEN(c, eptr, len) c = *eptr; #define BACKCHAR(eptr) #else /* SUPPORT_UTF8 */ /* Get the next UTF-8 character, not advancing the pointer. This is called when we know we are in UTF-8 mode. */ #define GETCHAR(c, eptr) \ c = *eptr; \ if ((c & 0xc0) == 0xc0) \ { \ int gcii; \ int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ int gcss = 6*gcaa; \ c = (c & utf8_table3[gcaa]) << gcss; \ for (gcii = 1; gcii <= gcaa; gcii++) \ { \ gcss -= 6; \ c |= (eptr[gcii] & 0x3f) << gcss; \ } \ } /* Get the next UTF-8 character, advancing the pointer. This is called when we know we are in UTF-8 mode. */ #define GETCHARINC(c, eptr) \ c = *eptr++; \ if ((c & 0xc0) == 0xc0) \ { \ int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ int gcss = 6*gcaa; \ c = (c & utf8_table3[gcaa]) << gcss; \ while (gcaa-- > 0) \ { \ gcss -= 6; \ c |= (*eptr++ & 0x3f) << gcss; \ } \ } /* Get the next character, testing for UTF-8 mode, and advancing the pointer */ #define GETCHARINCTEST(c, eptr) \ c = *eptr++; \ if (md->utf8 && (c & 0xc0) == 0xc0) \ { \ int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ int gcss = 6*gcaa; \ c = (c & utf8_table3[gcaa]) << gcss; \ while (gcaa-- > 0) \ { \ gcss -= 6; \ c |= (*eptr++ & 0x3f) << gcss; \ } \ } /* Get the next UTF-8 character, not advancing the pointer, incrementing length if there are extra bytes. This is called when we know we are in UTF-8 mode. */ #define GETCHARLEN(c, eptr, len) \ c = *eptr; \ if ((c & 0xc0) == 0xc0) \ { \ int gcii; \ int gcaa = utf8_table4[c & 0x3f]; /* Number of additional bytes */ \ int gcss = 6*gcaa; \ c = (c & utf8_table3[gcaa]) << gcss; \ for (gcii = 1; gcii <= gcaa; gcii++) \ { \ gcss -= 6; \ c |= (eptr[gcii] & 0x3f) << gcss; \ } \ len += gcaa; \ } /* If the pointer is not at the start of a character, move it back until it is. Called only in UTF-8 mode. */ #define BACKCHAR(eptr) while((*eptr & 0xc0) == 0x80) eptr--; #endif /************************************************* * Default character tables * *************************************************/ /* A default set of character tables is included in the PCRE binary. Its source is built by the maketables auxiliary program, which uses the default C ctypes functions, and put in the file chartables.c. These tables are used by PCRE whenever the caller of pcre_compile() does not provide an alternate set of tables. */ #include "chartables.c" #ifdef SUPPORT_UTF8 /************************************************* * Tables for UTF-8 support * *************************************************/ /* These are the breakpoints for different numbers of bytes in a UTF-8 character. */ static const int utf8_table1[] = { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff}; /* These are the indicator bits and the mask for the data bits to set in the first byte of a character, indexed by the number of additional bytes. */ static const int utf8_table2[] = { 0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}; static const int utf8_table3[] = { 0xff, 0x1f, 0x0f, 0x07, 0x03, 0x01}; /* Table of the number of extra characters, indexed by the first character masked with 0x3f. The highest number for a valid UTF-8 character is in fact 0x3d. */ static const uschar utf8_table4[] = { 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, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; /************************************************* * Convert character value to UTF-8 * *************************************************/ /* This function takes an integer value in the range 0 - 0x7fffffff and encodes it as a UTF-8 character in 0 to 6 bytes. Arguments: cvalue the character value buffer pointer to buffer for result - at least 6 bytes long Returns: number of characters placed in the buffer */ static int ord2utf8(int cvalue, uschar *buffer) { register int i, j; for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++) if (cvalue <= utf8_table1[i]) break; buffer += i; for (j = i; j > 0; j--) { *buffer-- = 0x80 | (cvalue & 0x3f); cvalue >>= 6; } *buffer = utf8_table2[i] | cvalue; return i + 1; } #endif /************************************************* * Print compiled regex * *************************************************/ /* The code for doing this is held in a separate file that is also included in pcretest.c. It defines a function called print_internals(). */ #ifdef DEBUG #include "printint.c" #endif /************************************************* * Return version string * *************************************************/ #define STRING(a) # a #define XSTRING(s) STRING(s) EXPORT const char * pcre_version(void) { return XSTRING(PCRE_MAJOR) "." XSTRING(PCRE_MINOR) " " XSTRING(PCRE_DATE); } /************************************************* * (Obsolete) Return info about compiled pattern * *************************************************/ /* This is the original "info" function. It picks potentially useful data out of the private structure, but its interface was too rigid. It remains for backwards compatibility. The public options are passed back in an int - though the re->options field has been expanded to a long int, all the public options at the low end of it, and so even on 16-bit systems this will still be OK. Therefore, I haven't changed the API for pcre_info(). Arguments: external_re points to compiled code optptr where to pass back the options first_byte where to pass back the first character, or -1 if multiline and all branches start ^, or -2 otherwise Returns: number of capturing subpatterns or negative values on error */ EXPORT int pcre_info(const pcre *external_re, int *optptr, int *first_byte) { const real_pcre *re = (const real_pcre *)external_re; if (re == NULL) return PCRE_ERROR_NULL; if (re->magic_number != MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; if (optptr != NULL) *optptr = (int)(re->options & PUBLIC_OPTIONS); if (first_byte != NULL) *first_byte = ((re->options & PCRE_FIRSTSET) != 0)? re->first_byte : ((re->options & PCRE_STARTLINE) != 0)? -1 : -2; return re->top_bracket; } /************************************************* * Return info about compiled pattern * *************************************************/ /* This is a newer "info" function which has an extensible interface so that additional items can be added compatibly. Arguments: external_re points to compiled code extra_data points extra data, or NULL what what information is required where where to put the information Returns: 0 if data returned, negative on error */ EXPORT int pcre_fullinfo(const pcre *external_re, const pcre_extra *extra_data, int what, void *where) { const real_pcre *re = (const real_pcre *)external_re; const pcre_study_data *study = NULL; if (re == NULL || where == NULL) return PCRE_ERROR_NULL; if (re->magic_number != MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; if (extra_data != NULL && (extra_data->flags & PCRE_EXTRA_STUDY_DATA) != 0) study = (const pcre_study_data *)extra_data->study_data; switch (what) { case PCRE_INFO_OPTIONS: *((unsigned long int *)where) = re->options & PUBLIC_OPTIONS; break; case PCRE_INFO_SIZE: *((size_t *)where) = re->size; break; case PCRE_INFO_STUDYSIZE: *((size_t *)where) = (study == NULL)? 0 : study->size; break; case PCRE_INFO_CAPTURECOUNT: *((int *)where) = re->top_bracket; break; case PCRE_INFO_BACKREFMAX: *((int *)where) = re->top_backref; break; case PCRE_INFO_FIRSTBYTE: *((int *)where) = ((re->options & PCRE_FIRSTSET) != 0)? re->first_byte : ((re->options & PCRE_STARTLINE) != 0)? -1 : -2; break; case PCRE_INFO_FIRSTTABLE: *((const uschar **)where) = (study != NULL && (study->options & PCRE_STUDY_MAPPED) != 0)? study->start_bits : NULL; break; case PCRE_INFO_LASTLITERAL: *((int *)where) = ((re->options & PCRE_REQCHSET) != 0)? re->req_byte : -1; break; case PCRE_INFO_NAMEENTRYSIZE: *((int *)where) = re->name_entry_size; break; case PCRE_INFO_NAMECOUNT: *((int *)where) = re->name_count; break; case PCRE_INFO_NAMETABLE: *((const uschar **)where) = (const uschar *)re + sizeof(real_pcre); break; default: return PCRE_ERROR_BADOPTION; } return 0; } /************************************************* * Return info about what features are configured * *************************************************/ /* This is function which has an extensible interface so that additional items can be added compatibly. Arguments: what what information is required where where to put the information Returns: 0 if data returned, negative on error */ EXPORT int pcre_config(int what, void *where) { switch (what) { case PCRE_CONFIG_UTF8: #ifdef SUPPORT_UTF8 *((int *)where) = 1; #else *((int *)where) = 0; #endif break; case PCRE_CONFIG_NEWLINE: *((int *)where) = NEWLINE; break; case PCRE_CONFIG_LINK_SIZE: *((int *)where) = LINK_SIZE; break; case PCRE_CONFIG_POSIX_MALLOC_THRESHOLD: *((int *)where) = POSIX_MALLOC_THRESHOLD; break; case PCRE_CONFIG_MATCH_LIMIT: *((unsigned int *)where) = MATCH_LIMIT; break; case PCRE_CONFIG_STACKRECURSE: #ifdef NO_RECURSE *((int *)where) = 0; #else *((int *)where) = 1; #endif break; default: return PCRE_ERROR_BADOPTION; } return 0; } #ifdef DEBUG /************************************************* * Debugging function to print chars * *************************************************/ /* Print a sequence of chars in printable format, stopping at the end of the subject if the requested. Arguments: p points to characters length number to print is_subject TRUE if printing from within md->start_subject md pointer to matching data block, if is_subject is TRUE Returns: nothing */ static void pchars(const uschar *p, int length, BOOL is_subject, match_data *md) { int c; if (is_subject && length > md->end_subject - p) length = md->end_subject - p; while (length-- > 0) if (isprint(c = *(p++))) printf("%c", c); else printf("\\x%02x", c); } #endif /************************************************* * Handle escapes * *************************************************/ /* This function is called when a \ has been encountered. It either returns a positive value for a simple escape such as \n, or a negative value which encodes one of the more complicated things such as \d. When UTF-8 is enabled, a positive value greater than 255 may be returned. On entry, ptr is pointing at the \. On exit, it is on the final character of the escape sequence. Arguments: ptrptr points to the pattern position pointer errorptr points to the pointer to the error message bracount number of previous extracting brackets options the options bits isclass TRUE if inside a character class Returns: zero or positive => a data character negative => a special escape sequence on error, errorptr is set */ static int check_escape(const uschar **ptrptr, const char **errorptr, int bracount, int options, BOOL isclass) { const uschar *ptr = *ptrptr; int c, i; /* If backslash is at the end of the pattern, it's an error. */ c = *(++ptr); if (c == 0) *errorptr = ERR1; /* Non-alphamerics are literals. For digits or letters, do an initial lookup in a table. A non-zero result is something that can be returned immediately. Otherwise further processing may be required. */ #if !EBCDIC /* ASCII coding */ else if (c < '0' || c > 'z') {} /* Not alphameric */ else if ((i = escapes[c - '0']) != 0) c = i; #else /* EBCDIC coding */ else if (c < 'a' || (ebcdic_chartab[c] & 0x0E) == 0) {} /* Not alphameric */ else if ((i = escapes[c - 0x48]) != 0) c = i; #endif /* Escapes that need further processing, or are illegal. */ else { const uschar *oldptr; switch (c) { /* A number of Perl escapes are not handled by PCRE. We give an explicit error. */ case 'l': case 'L': case 'N': case 'p': case 'P': case 'u': case 'U': case 'X': *errorptr = ERR37; break; /* The handling of escape sequences consisting of a string of digits starting with one that is not zero is not straightforward. By experiment, the way Perl works seems to be as follows: Outside a character class, the digits are read as a decimal number. If the number is less than 10, or if there are that many previous extracting left brackets, then it is a back reference. Otherwise, up to three octal digits are read to form an escaped byte. Thus \123 is likely to be octal 123 (cf \0123, which is octal 012 followed by the literal 3). If the octal value is greater than 377, the least significant 8 bits are taken. Inside a character class, \ followed by a digit is always an octal number. */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (!isclass) { oldptr = ptr; c -= '0'; while ((digitab[ptr[1]] & ctype_digit) != 0) c = c * 10 + *(++ptr) - '0'; if (c < 10 || c <= bracount) { c = -(ESC_REF + c); break; } ptr = oldptr; /* Put the pointer back and fall through */ } /* Handle an octal number following \. If the first digit is 8 or 9, Perl generates a binary zero byte and treats the digit as a following literal. Thus we have to pull back the pointer by one. */ if ((c = *ptr) >= '8') { ptr--; c = 0; break; } /* \0 always starts an octal number, but we may drop through to here with a larger first octal digit. */ case '0': c -= '0'; while(i++ < 2 && ptr[1] >= '0' && ptr[1] <= '7') c = c * 8 + *(++ptr) - '0'; c &= 255; /* Take least significant 8 bits */ break; /* \x is complicated when UTF-8 is enabled. \x{ddd} is a character number which can be greater than 0xff, but only if the ddd are hex digits. */ case 'x': #ifdef SUPPORT_UTF8 if (ptr[1] == '{' && (options & PCRE_UTF8) != 0) { const uschar *pt = ptr + 2; register int count = 0; c = 0; while ((digitab[*pt] & ctype_xdigit) != 0) { int cc = *pt++; count++; #if !EBCDIC /* ASCII coding */ if (cc >= 'a') cc -= 32; /* Convert to upper case */ c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10)); #else /* EBCDIC coding */ if (cc >= 'a' && cc <= 'z') cc += 64; /* Convert to upper case */ c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10)); #endif } if (*pt == '}') { if (c < 0 || count > 8) *errorptr = ERR34; ptr = pt; break; } /* If the sequence of hex digits does not end with '}', then we don't recognize this construct; fall through to the normal \x handling. */ } #endif /* Read just a single hex char */ c = 0; while (i++ < 2 && (digitab[ptr[1]] & ctype_xdigit) != 0) { int cc; /* Some compilers don't like ++ */ cc = *(++ptr); /* in initializers */ #if !EBCDIC /* ASCII coding */ if (cc >= 'a') cc -= 32; /* Convert to upper case */ c = c * 16 + cc - ((cc < 'A')? '0' : ('A' - 10)); #else /* EBCDIC coding */ if (cc <= 'z') cc += 64; /* Convert to upper case */ c = c * 16 + cc - ((cc >= '0')? '0' : ('A' - 10)); #endif } break; /* Other special escapes not starting with a digit are straightforward */ case 'c': c = *(++ptr); if (c == 0) { *errorptr = ERR2; return 0; } /* A letter is upper-cased; then the 0x40 bit is flipped. This coding is ASCII-specific, but then the whole concept of \cx is ASCII-specific. (However, an EBCDIC equivalent has now been added.) */ #if !EBCDIC /* ASCII coding */ if (c >= 'a' && c <= 'z') c -= 32; c ^= 0x40; #else /* EBCDIC coding */ if (c >= 'a' && c <= 'z') c += 64; c ^= 0xC0; #endif break; /* PCRE_EXTRA enables extensions to Perl in the matter of escapes. Any other alphameric following \ is an error if PCRE_EXTRA was set; otherwise, for Perl compatibility, it is a literal. This code looks a bit odd, but there used to be some cases other than the default, and there may be again in future, so I haven't "optimized" it. */ default: if ((options & PCRE_EXTRA) != 0) switch(c) { default: *errorptr = ERR3; break; } break; } } *ptrptr = ptr; return c; } /************************************************* * Check for counted repeat * *************************************************/ /* This function is called when a '{' is encountered in a place where it might start a quantifier. It looks ahead to see if it really is a quantifier or not. It is only a quantifier if it is one of the forms {ddd} {ddd,} or {ddd,ddd} where the ddds are digits. Arguments: p pointer to the first char after '{' Returns: TRUE or FALSE */ static BOOL is_counted_repeat(const uschar *p) { if ((digitab[*p++] & ctype_digit) == 0) return FALSE; while ((digitab[*p] & ctype_digit) != 0) p++; if (*p == '}') return TRUE; if (*p++ != ',') return FALSE; if (*p == '}') return TRUE; if ((digitab[*p++] & ctype_digit) == 0) return FALSE; while ((digitab[*p] & ctype_digit) != 0) p++; return (*p == '}'); } /************************************************* * Read repeat counts * *************************************************/ /* Read an item of the form {n,m} and return the values. This is called only after is_counted_repeat() has confirmed that a repeat-count quantifier exists, so the syntax is guaranteed to be correct, but we need to check the values. Arguments: p pointer to first char after '{' minp pointer to int for min maxp pointer to int for max returned as -1 if no max errorptr points to pointer to error message Returns: pointer to '}' on success; current ptr on error, with errorptr set */ static const uschar * read_repeat_counts(const uschar *p, int *minp, int *maxp, const char **errorptr) { int min = 0; int max = -1; while ((digitab[*p] & ctype_digit) != 0) min = min * 10 + *p++ - '0'; if (*p == '}') max = min; else { if (*(++p) != '}') { max = 0; while((digitab[*p] & ctype_digit) != 0) max = max * 10 + *p++ - '0'; if (max < min) { *errorptr = ERR4; return p; } } } /* Do paranoid checks, then fill in the required variables, and pass back the pointer to the terminating '}'. */ if (min > 65535 || max > 65535) *errorptr = ERR5; else { *minp = min; *maxp = max; } return p; } /************************************************* * Find first significant op code * *************************************************/ /* This is called by several functions that scan a compiled expression looking for a fixed first character, or an anchoring op code etc. It skips over things that do not influence this. For some calls, a change of option is important. Arguments: code pointer to the start of the group options pointer to external options optbit the option bit whose changing is significant, or zero if none are Returns: pointer to the first significant opcode */ static const uschar* first_significant_code(const uschar *code, int *options, int optbit) { for (;;) { switch ((int)*code) { case OP_OPT: if (optbit > 0 && ((int)code[1] & optbit) != (*options & optbit)) *options = (int)code[1]; code += 2; break; case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: do code += GET(code, 1); while (*code == OP_ALT); /* Fall through */ case OP_CALLOUT: case OP_CREF: case OP_BRANUMBER: case OP_WORD_BOUNDARY: case OP_NOT_WORD_BOUNDARY: code += OP_lengths[*code]; break; default: return code; } } /* Control never reaches here */ } /************************************************* * Find the fixed length of a pattern * *************************************************/ /* Scan a pattern and compute the fixed length of subject that will match it, if the length is fixed. This is needed for dealing with backward assertions. In UTF8 mode, the result is in characters rather than bytes. Arguments: code points to the start of the pattern (the bracket) options the compiling options Returns: the fixed length, or -1 if there is no fixed length, or -2 if \C was encountered */ static int find_fixedlength(uschar *code, int options) { int length = -1; register int branchlength = 0; register uschar *cc = code + 1 + LINK_SIZE; /* Scan along the opcodes for this branch. If we get to the end of the branch, check the length against that of the other branches. */ for (;;) { int d; register int op = *cc; if (op >= OP_BRA) op = OP_BRA; switch (op) { case OP_BRA: case OP_ONCE: case OP_COND: d = find_fixedlength(cc, options); if (d < 0) return d; branchlength += d; do cc += GET(cc, 1); while (*cc == OP_ALT); cc += 1 + LINK_SIZE; break; /* Reached end of a branch; if it's a ket it is the end of a nested call. If it's ALT it is an alternation in a nested call. If it is END it's the end of the outer call. All can be handled by the same code. */ case OP_ALT: case OP_KET: case OP_KETRMAX: case OP_KETRMIN: case OP_END: if (length < 0) length = branchlength; else if (length != branchlength) return -1; if (*cc != OP_ALT) return length; cc += 1 + LINK_SIZE; branchlength = 0; break; /* Skip over assertive subpatterns */ case OP_ASSERT: case OP_ASSERT_NOT: case OP_ASSERTBACK: case OP_ASSERTBACK_NOT: do cc += GET(cc, 1); while (*cc == OP_ALT); /* Fall through */ /* Skip over things that don't match chars */ case OP_REVERSE: case OP_BRANUMBER: case OP_CREF: case OP_OPT: case OP_CALLOUT: case OP_SOD: case OP_SOM: case OP_EOD: case OP_EODN: case OP_CIRC: case OP_DOLL: case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: cc += OP_lengths[*cc]; break; /* Handle char strings. In UTF-8 mode we must count characters, not bytes. This requires a scan of the string, unfortunately. We assume valid UTF-8 strings, so all we do is reduce the length by one for every byte whose bits are 10xxxxxx. */ case OP_CHARS: branchlength += *(++cc); #ifdef SUPPORT_UTF8 if ((options & PCRE_UTF8) != 0) for (d = 1; d <= *cc; d++) if ((cc[d] & 0xc0) == 0x80) branchlength--; #endif cc += *cc + 1; break; /* Handle exact repetitions. The count is already in characters, but we need to skip over a multibyte character in UTF8 mode. */ case OP_EXACT: branchlength += GET2(cc,1); cc += 4; #ifdef SUPPORT_UTF8 if ((options & PCRE_UTF8) != 0) { while((*cc & 0x80) == 0x80) cc++; } #endif break; case OP_TYPEEXACT: branchlength += GET2(cc,1); cc += 4; break; /* Handle single-char matchers */ case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: branchlength++; cc++; break; /* The single-byte matcher isn't allowed */ case OP_ANYBYTE: return -2; /* Check a class for variable quantification */ #ifdef SUPPORT_UTF8 case OP_XCLASS: cc += GET(cc, 1) - 33; /* Fall through */ #endif case OP_CLASS: case OP_NCLASS: cc += 33; switch (*cc) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRQUERY: case OP_CRMINQUERY: return -1; case OP_CRRANGE: case OP_CRMINRANGE: if (GET2(cc,1) != GET2(cc,3)) return -1; branchlength += GET2(cc,1); cc += 5; break; default: branchlength++; } break; /* Anything else is variable length */ default: return -1; } } /* Control never gets here */ } /************************************************* * Scan compiled regex for numbered bracket * *************************************************/ /* This little function scans through a compiled pattern until it finds a capturing bracket with the given number. Arguments: code points to start of expression utf8 TRUE in UTF-8 mode number the required bracket number Returns: pointer to the opcode for the bracket, or NULL if not found */ static const uschar * find_bracket(const uschar *code, BOOL utf8, int number) { #ifndef SUPPORT_UTF8 utf8 = utf8; /* Stop pedantic compilers complaining */ #endif for (;;) { register int c = *code; if (c == OP_END) return NULL; else if (c == OP_CHARS) code += code[1] + OP_lengths[c]; else if (c > OP_BRA) { int n = c - OP_BRA; if (n > EXTRACT_BASIC_MAX) n = GET2(code, 2+LINK_SIZE); if (n == number) return (uschar *)code; code += OP_lengths[OP_BRA]; } else { code += OP_lengths[c]; #ifdef SUPPORT_UTF8 /* In UTF-8 mode, opcodes that are followed by a character may be followed by a multi-byte character. The length in the table is a minimum, so we have to scan along to skip the extra characters. All opcodes are less than 128, so we can use relatively efficient code. */ if (utf8) switch(c) { case OP_EXACT: case OP_UPTO: case OP_MINUPTO: case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: while ((*code & 0xc0) == 0x80) code++; break; /* XCLASS is used for classes that cannot be represented just by a bit map. This includes negated single high-valued characters. The length in the table is zero; the actual length is stored in the compled code. */ case OP_XCLASS: code += GET(code, 1) + 1; break; } #endif } } } /************************************************* * Scan compiled regex for recursion reference * *************************************************/ /* This little function scans through a compiled pattern until it finds an instance of OP_RECURSE. Arguments: code points to start of expression utf8 TRUE in UTF-8 mode Returns: pointer to the opcode for OP_RECURSE, or NULL if not found */ static const uschar * find_recurse(const uschar *code, BOOL utf8) { #ifndef SUPPORT_UTF8 utf8 = utf8; /* Stop pedantic compilers complaining */ #endif for (;;) { register int c = *code; if (c == OP_END) return NULL; else if (c == OP_RECURSE) return code; else if (c == OP_CHARS) code += code[1] + OP_lengths[c]; else if (c > OP_BRA) { code += OP_lengths[OP_BRA]; } else { code += OP_lengths[c]; #ifdef SUPPORT_UTF8 /* In UTF-8 mode, opcodes that are followed by a character may be followed by a multi-byte character. The length in the table is a minimum, so we have to scan along to skip the extra characters. All opcodes are less than 128, so we can use relatively efficient code. */ if (utf8) switch(c) { case OP_EXACT: case OP_UPTO: case OP_MINUPTO: case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: while ((*code & 0xc0) == 0x80) code++; break; /* XCLASS is used for classes that cannot be represented just by a bit map. This includes negated single high-valued characters. The length in the table is zero; the actual length is stored in the compled code. */ case OP_XCLASS: code += GET(code, 1) + 1; break; } #endif } } } /************************************************* * Scan compiled branch for non-emptiness * *************************************************/ /* This function scans through a branch of a compiled pattern to see whether it can match the empty string or not. It is called only from could_be_empty() below. Note that first_significant_code() skips over assertions. If we hit an unclosed bracket, we return "empty" - this means we've struck an inner bracket whose current branch will already have been scanned. Arguments: code points to start of search endcode points to where to stop utf8 TRUE if in UTF8 mode Returns: TRUE if what is matched could be empty */ static BOOL could_be_empty_branch(const uschar *code, const uschar *endcode, BOOL utf8) { register int c; for (code = first_significant_code(code + 1 + LINK_SIZE, NULL, 0); code < endcode; code = first_significant_code(code + OP_lengths[c], NULL, 0)) { const uschar *ccode; c = *code; if (c >= OP_BRA) { BOOL empty_branch; if (GET(code, 1) == 0) return TRUE; /* Hit unclosed bracket */ /* Scan a closed bracket */ empty_branch = FALSE; do { if (!empty_branch && could_be_empty_branch(code, endcode, utf8)) empty_branch = TRUE; code += GET(code, 1); } while (*code == OP_ALT); if (!empty_branch) return FALSE; /* All branches are non-empty */ code += 1 + LINK_SIZE; c = *code; } else switch (c) { /* Check for quantifiers after a class */ #ifdef SUPPORT_UTF8 case OP_XCLASS: ccode = code + GET(code, 1); goto CHECK_CLASS_REPEAT; #endif case OP_CLASS: case OP_NCLASS: ccode = code + 33; #ifdef SUPPORT_UTF8 CHECK_CLASS_REPEAT: #endif switch (*ccode) { case OP_CRSTAR: /* These could be empty; continue */ case OP_CRMINSTAR: case OP_CRQUERY: case OP_CRMINQUERY: break; default: /* Non-repeat => class must match */ case OP_CRPLUS: /* These repeats aren't empty */ case OP_CRMINPLUS: return FALSE; case OP_CRRANGE: case OP_CRMINRANGE: if (GET2(ccode, 1) > 0) return FALSE; /* Minimum > 0 */ break; } break; /* Opcodes that must match a character */ case OP_NOT_DIGIT: case OP_DIGIT: case OP_NOT_WHITESPACE: case OP_WHITESPACE: case OP_NOT_WORDCHAR: case OP_WORDCHAR: case OP_ANY: case OP_ANYBYTE: case OP_CHARS: case OP_NOT: case OP_PLUS: case OP_MINPLUS: case OP_EXACT: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTEXACT: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEEXACT: return FALSE; /* End of branch */ case OP_KET: case OP_KETRMAX: case OP_KETRMIN: case OP_ALT: return TRUE; /* In UTF-8 mode, STAR, MINSTAR, QUERY, MINQUERY, UPTO, and MINUPTO may be followed by a multibyte character */ #ifdef SUPPORT_UTF8 case OP_STAR: case OP_MINSTAR: case OP_QUERY: case OP_MINQUERY: case OP_UPTO: case OP_MINUPTO: if (utf8) while ((code[2] & 0xc0) == 0x80) code++; break; #endif } } return TRUE; } /************************************************* * Scan compiled regex for non-emptiness * *************************************************/ /* This function is called to check for left recursive calls. We want to check the current branch of the current pattern to see if it could match the empty string. If it could, we must look outwards for branches at other levels, stopping when we pass beyond the bracket which is the subject of the recursion. Arguments: code points to start of the recursion endcode points to where to stop (current RECURSE item) bcptr points to the chain of current (unclosed) branch starts utf8 TRUE if in UTF-8 mode Returns: TRUE if what is matched could be empty */ static BOOL could_be_empty(const uschar *code, const uschar *endcode, branch_chain *bcptr, BOOL utf8) { while (bcptr != NULL && bcptr->current >= code) { if (!could_be_empty_branch(bcptr->current, endcode, utf8)) return FALSE; bcptr = bcptr->outer; } return TRUE; } /************************************************* * Check for POSIX class syntax * *************************************************/ /* This function is called when the sequence "[:" or "[." or "[=" is encountered in a character class. It checks whether this is followed by an optional ^ and then a sequence of letters, terminated by a matching ":]" or ".]" or "=]". Argument: ptr pointer to the initial [ endptr where to return the end pointer cd pointer to compile data Returns: TRUE or FALSE */ static BOOL check_posix_syntax(const uschar *ptr, const uschar **endptr, compile_data *cd) { int terminator; /* Don't combine these lines; the Solaris cc */ terminator = *(++ptr); /* compiler warns about "non-constant" initializer. */ if (*(++ptr) == '^') ptr++; while ((cd->ctypes[*ptr] & ctype_letter) != 0) ptr++; if (*ptr == terminator && ptr[1] == ']') { *endptr = ptr; return TRUE; } return FALSE; } /************************************************* * Check POSIX class name * *************************************************/ /* This function is called to check the name given in a POSIX-style class entry such as [:alnum:]. Arguments: ptr points to the first letter len the length of the name Returns: a value representing the name, or -1 if unknown */ static int check_posix_name(const uschar *ptr, int len) { register int yield = 0; while (posix_name_lengths[yield] != 0) { if (len == posix_name_lengths[yield] && strncmp((const char *)ptr, posix_names[yield], len) == 0) return yield; yield++; } return -1; } /************************************************* * Adjust OP_RECURSE items in repeated group * *************************************************/ /* OP_RECURSE items contain an offset from the start of the regex to the group that is referenced. This means that groups can be replicated for fixed repetition simply by copying (because the recursion is allowed to refer to earlier groups that are outside the current group). However, when a group is optional (i.e. the minimum quantifier is zero), OP_BRAZERO is inserted before it, after it has been compiled. This means that any OP_RECURSE items within it that refer to the group itself or any contained groups have to have their offsets adjusted. That is the job of this function. Before it is called, the partially compiled regex must be temporarily terminated with OP_END. Arguments: group points to the start of the group adjust the amount by which the group is to be moved utf8 TRUE in UTF-8 mode cd contains pointers to tables etc. Returns: nothing */ static void adjust_recurse(uschar *group, int adjust, BOOL utf8, compile_data *cd) { uschar *ptr = group; while ((ptr = (uschar *)find_recurse(ptr, utf8)) != NULL) { int offset = GET(ptr, 1); if (cd->start_code + offset >= group) PUT(ptr, 1, offset + adjust); ptr += 1 + LINK_SIZE; } } /************************************************* * Compile one branch * *************************************************/ /* Scan the pattern, compiling it into the code vector. If the options are changed during the branch, the pointer is used to change the external options bits. Arguments: optionsptr pointer to the option bits brackets points to number of extracting brackets used code points to the pointer to the current code point ptrptr points to the current pattern pointer errorptr points to pointer to error message firstbyteptr set to initial literal character, or < 0 (REQ_UNSET, REQ_NONE) reqbyteptr set to the last literal character required, else < 0 bcptr points to current branch chain cd contains pointers to tables etc. Returns: TRUE on success FALSE, with *errorptr set on error */ static BOOL compile_branch(int *optionsptr, int *brackets, uschar **codeptr, const uschar **ptrptr, const char **errorptr, int *firstbyteptr, int *reqbyteptr, branch_chain *bcptr, compile_data *cd) { int repeat_type, op_type; int repeat_min = 0, repeat_max = 0; /* To please picky compilers */ int bravalue = 0; int length; int greedy_default, greedy_non_default; int firstbyte, reqbyte; int zeroreqbyte, zerofirstbyte; int req_caseopt, reqvary, tempreqvary; int condcount = 0; int options = *optionsptr; register int c; register uschar *code = *codeptr; uschar *tempcode; BOOL inescq = FALSE; BOOL groupsetfirstbyte = FALSE; const uschar *ptr = *ptrptr; const uschar *tempptr; uschar *previous = NULL; uschar class[32]; #ifdef SUPPORT_UTF8 BOOL class_utf8; BOOL utf8 = (options & PCRE_UTF8) != 0; uschar *class_utf8data; uschar utf8_char[6]; #else BOOL utf8 = FALSE; #endif /* Set up the default and non-default settings for greediness */ greedy_default = ((options & PCRE_UNGREEDY) != 0); greedy_non_default = greedy_default ^ 1; /* Initialize no first char, no required char. REQ_UNSET means "no char matching encountered yet". It gets changed to REQ_NONE if we hit something that matches a non-fixed char first char; reqbyte just remains unset if we never find one. When we hit a repeat whose minimum is zero, we may have to adjust these values to take the zero repeat into account. This is implemented by setting them to zerofirstbyte and zeroreqbyte when such a repeat is encountered. The individual item types that can be repeated set these backoff variables appropriately. */ firstbyte = reqbyte = zerofirstbyte = zeroreqbyte = REQ_UNSET; /* The variable req_caseopt contains either the REQ_CASELESS value or zero, according to the current setting of the caseless flag. REQ_CASELESS is a bit value > 255. It is added into the firstbyte or reqbyte variables to record the case status of the value. */ req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0; /* Switch on next character until the end of the branch */ for (;; ptr++) { BOOL negate_class; BOOL possessive_quantifier; int class_charcount; int class_lastchar; int newoptions; int recno; int skipbytes; int subreqbyte; int subfirstbyte; c = *ptr; if (inescq && c != 0) goto NORMAL_CHAR; if ((options & PCRE_EXTENDED) != 0) { if ((cd->ctypes[c] & ctype_space) != 0) continue; if (c == '#') { /* The space before the ; is to avoid a warning on a silly compiler on the Macintosh. */ while ((c = *(++ptr)) != 0 && c != NEWLINE) ; if (c != 0) continue; /* Else fall through to handle end of string */ } } switch(c) { /* The branch terminates at end of string, |, or ). */ case 0: case '|': case ')': *firstbyteptr = firstbyte; *reqbyteptr = reqbyte; *codeptr = code; *ptrptr = ptr; return TRUE; /* Handle single-character metacharacters. In multiline mode, ^ disables the setting of any following char as a first character. */ case '^': if ((options & PCRE_MULTILINE) != 0) { if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; } previous = NULL; *code++ = OP_CIRC; break; case '$': previous = NULL; *code++ = OP_DOLL; break; /* There can never be a first char if '.' is first, whatever happens about repeats. The value of reqbyte doesn't change either. */ case '.': if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; zerofirstbyte = firstbyte; zeroreqbyte = reqbyte; previous = code; *code++ = OP_ANY; break; /* Character classes. If the included characters are all < 255 in value, we build a 32-byte bitmap of the permitted characters, except in the special case where there is only one such character. For negated classes, we build the map as usual, then invert it at the end. However, we use a different opcode so that data characters > 255 can be handled correctly. If the class contains characters outside the 0-255 range, a different opcode is compiled. It may optionally have a bit map for characters < 256, but those above are are explicitly listed afterwards. A flag byte tells whether the bitmap is present, and whether this is a negated class or not. */ case '[': previous = code; /* PCRE supports POSIX class stuff inside a class. Perl gives an error if they are encountered at the top level, so we'll do that too. */ if ((ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') && check_posix_syntax(ptr, &tempptr, cd)) { *errorptr = (ptr[1] == ':')? ERR13 : ERR31; goto FAILED; } /* If the first character is '^', set the negation flag and skip it. */ if ((c = *(++ptr)) == '^') { negate_class = TRUE; c = *(++ptr); } else { negate_class = FALSE; } /* Keep a count of chars with values < 256 so that we can optimize the case of just a single character (as long as it's < 256). For higher valued UTF-8 characters, we don't yet do any optimization. */ class_charcount = 0; class_lastchar = -1; #ifdef SUPPORT_UTF8 class_utf8 = FALSE; /* No chars >= 256 */ class_utf8data = code + LINK_SIZE + 34; /* For UTF-8 items */ #endif /* Initialize the 32-char bit map to all zeros. We have to build the map in a temporary bit of store, in case the class contains only 1 character (< 256), because in that case the compiled code doesn't use the bit map. */ memset(class, 0, 32 * sizeof(uschar)); /* Process characters until ] is reached. By writing this as a "do" it means that an initial ] is taken as a data character. The first pass through the regex checked the overall syntax, so we don't need to be very strict here. At the start of the loop, c contains the first byte of the character. */ do { #ifdef SUPPORT_UTF8 if (utf8 && c > 127) { /* Braces are required because the */ GETCHARLEN(c, ptr, ptr); /* macro generates multiple statements */ } #endif /* Inside \Q...\E everything is literal except \E */ if (inescq) { if (c == '\\' && ptr[1] == 'E') { inescq = FALSE; ptr++; continue; } else goto LONE_SINGLE_CHARACTER; } /* Handle POSIX class names. Perl allows a negation extension of the form [:^name:]. A square bracket that doesn't match the syntax is treated as a literal. We also recognize the POSIX constructions [.ch.] and [=ch=] ("collating elements") and fault them, as Perl 5.6 and 5.8 do. */ if (c == '[' && (ptr[1] == ':' || ptr[1] == '.' || ptr[1] == '=') && check_posix_syntax(ptr, &tempptr, cd)) { BOOL local_negate = FALSE; int posix_class, i; register const uschar *cbits = cd->cbits; if (ptr[1] != ':') { *errorptr = ERR31; goto FAILED; } ptr += 2; if (*ptr == '^') { local_negate = TRUE; ptr++; } posix_class = check_posix_name(ptr, tempptr - ptr); if (posix_class < 0) { *errorptr = ERR30; goto FAILED; } /* If matching is caseless, upper and lower are converted to alpha. This relies on the fact that the class table starts with alpha, lower, upper as the first 3 entries. */ if ((options & PCRE_CASELESS) != 0 && posix_class <= 2) posix_class = 0; /* Or into the map we are building up to 3 of the static class tables, or their negations. The [:blank:] class sets up the same chars as the [:space:] class (all white space). We remove the vertical white space chars afterwards. */ posix_class *= 3; for (i = 0; i < 3; i++) { BOOL blankclass = strncmp((char *)ptr, "blank", 5) == 0; int taboffset = posix_class_maps[posix_class + i]; if (taboffset < 0) break; if (local_negate) { for (c = 0; c < 32; c++) class[c] |= ~cbits[c+taboffset]; if (blankclass) class[1] |= 0x3c; } else { for (c = 0; c < 32; c++) class[c] |= cbits[c+taboffset]; if (blankclass) class[1] &= ~0x3c; } } ptr = tempptr + 1; class_charcount = 10; /* Set > 1; assumes more than 1 per class */ continue; /* End of POSIX syntax handling */ } /* Backslash may introduce a single character, or it may introduce one of the specials, which just set a flag. Escaped items are checked for validity in the pre-compiling pass. The sequence \b is a special case. Inside a class (and only there) it is treated as backspace. Elsewhere it marks a word boundary. Other escapes have preset maps ready to or into the one we are building. We assume they have more than one character in them, so set class_charcount bigger than one. */ if (c == '\\') { c = check_escape(&ptr, errorptr, *brackets, options, TRUE); if (-c == ESC_b) c = '\b'; /* \b is backslash in a class */ if (-c == ESC_Q) /* Handle start of quoted string */ { if (ptr[1] == '\\' && ptr[2] == 'E') { ptr += 2; /* avoid empty string */ } else inescq = TRUE; continue; } else if (c < 0) { register const uschar *cbits = cd->cbits; class_charcount = 10; /* Greater than 1 is what matters */ switch (-c) { case ESC_d: for (c = 0; c < 32; c++) class[c] |= cbits[c+cbit_digit]; continue; case ESC_D: for (c = 0; c < 32; c++) class[c] |= ~cbits[c+cbit_digit]; continue; case ESC_w: for (c = 0; c < 32; c++) class[c] |= cbits[c+cbit_word]; continue; case ESC_W: for (c = 0; c < 32; c++) class[c] |= ~cbits[c+cbit_word]; continue; case ESC_s: for (c = 0; c < 32; c++) class[c] |= cbits[c+cbit_space]; class[1] &= ~0x08; /* Perl 5.004 onwards omits VT from \s */ continue; case ESC_S: for (c = 0; c < 32; c++) class[c] |= ~cbits[c+cbit_space]; class[1] |= 0x08; /* Perl 5.004 onwards omits VT from \s */ continue; /* Unrecognized escapes are faulted if PCRE is running in its strict mode. By default, for compatibility with Perl, they are treated as literals. */ default: if ((options & PCRE_EXTRA) != 0) { *errorptr = ERR7; goto FAILED; } c = *ptr; /* The final character */ } } /* Fall through if we have a single character (c >= 0). This may be > 256 in UTF-8 mode. */ } /* End of backslash handling */ /* A single character may be followed by '-' to form a range. However, Perl does not permit ']' to be the end of the range. A '-' character here is treated as a literal. */ if (ptr[1] == '-' && ptr[2] != ']') { int d; ptr += 2; #ifdef SUPPORT_UTF8 if (utf8) { /* Braces are required because the */ GETCHARLEN(d, ptr, ptr); /* macro generates multiple statements */ } else #endif d = *ptr; /* The second part of a range can be a single-character escape, but not any of the other escapes. Perl 5.6 treats a hyphen as a literal in such circumstances. */ if (d == '\\') { const uschar *oldptr = ptr; d = check_escape(&ptr, errorptr, *brackets, options, TRUE); /* \b is backslash; any other special means the '-' was literal */ if (d < 0) { if (d == -ESC_b) d = '\b'; else { ptr = oldptr - 2; goto LONE_SINGLE_CHARACTER; /* A few lines below */ } } } /* Check that the two values are in the correct order */ if (d < c) { *errorptr = ERR8; goto FAILED; } /* If d is greater than 255, we can't just use the bit map, so set up for the UTF-8 supporting class type. If we are not caseless, we can just set up a single range. If we are caseless, the characters < 256 are handled with a bitmap, in order to get the case-insensitive handling. */ #ifdef SUPPORT_UTF8 if (d > 255) { class_utf8 = TRUE; *class_utf8data++ = XCL_RANGE; if ((options & PCRE_CASELESS) == 0) { class_utf8data += ord2utf8(c, class_utf8data); class_utf8data += ord2utf8(d, class_utf8data); continue; /* Go get the next char in the class */ } class_utf8data += ord2utf8(256, class_utf8data); class_utf8data += ord2utf8(d, class_utf8data); d = 255; /* Fall through */ } #endif /* We use the bit map if the range is entirely < 255, or if part of it is < 255 and matching is caseless. */ for (; c <= d; c++) { class[c/8] |= (1 << (c&7)); if ((options & PCRE_CASELESS) != 0) { int uc = cd->fcc[c]; /* flip case */ class[uc/8] |= (1 << (uc&7)); } class_charcount++; /* in case a one-char range */ class_lastchar = c; } continue; /* Go get the next char in the class */ } /* Handle a lone single character - we can get here for a normal non-escape char, or after \ that introduces a single character. */ LONE_SINGLE_CHARACTER: /* Handle a multibyte character */ #ifdef SUPPORT_UTF8 if (utf8 && c > 255) { class_utf8 = TRUE; *class_utf8data++ = XCL_SINGLE; class_utf8data += ord2utf8(c, class_utf8data); } else #endif /* Handle a single-byte character */ { class [c/8] |= (1 << (c&7)); if ((options & PCRE_CASELESS) != 0) { c = cd->fcc[c]; /* flip case */ class[c/8] |= (1 << (c&7)); } class_charcount++; class_lastchar = c; } } /* Loop until ']' reached; the check for end of string happens inside the loop. This "while" is the end of the "do" above. */ while ((c = *(++ptr)) != ']' || inescq); /* If class_charcount is 1, we saw precisely one character with a value < 256. In UTF-8 mode, we can optimize if there were no characters >= 256 and the one character is < 128. In non-UTF-8 mode we can always optimize. The optimization throws away the bit map. We turn the item into a 1-character OP_CHARS if it's positive, or OP_NOT if it's negative. Note that OP_NOT does not support multibyte characters. In the positive case, it can cause firstbyte to be set. Otherwise, there can be no first char if this item is first, whatever repeat count may follow. In the case of reqbyte, save the previous value for reinstating. */ #ifdef SUPPORT_UTF8 if (class_charcount == 1 && (!utf8 || (!class_utf8 && class_lastchar < 128))) #else if (class_charcount == 1) #endif { zeroreqbyte = reqbyte; if (negate_class) { if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; zerofirstbyte = firstbyte; *code++ = OP_NOT; } else { if (firstbyte == REQ_UNSET) { zerofirstbyte = REQ_NONE; firstbyte = class_lastchar | req_caseopt; } else { zerofirstbyte = firstbyte; reqbyte = class_lastchar | req_caseopt | cd->req_varyopt; } *code++ = OP_CHARS; *code++ = 1; } *code++ = class_lastchar; break; /* End of class handling */ } /* End of 1-byte optimization */ /* Otherwise, if this is the first thing in the branch, there can be no first char setting, whatever the repeat count. Any reqbyte setting must remain unchanged after any kind of repeat. */ if (firstbyte == REQ_UNSET) firstbyte = REQ_NONE; zerofirstbyte = firstbyte; zeroreqbyte = reqbyte; /* If there are characters with values > 255, we have to compile an extended class, with its own opcode. If there are no characters < 256, we can omit the bitmap. */ #ifdef SUPPORT_UTF8 if (class_utf8) { *class_utf8data++ = XCL_END; /* Marks the end of extra data */ *code++ = OP_XCLASS; code += LINK_SIZE; *code = negate_class? XCL_NOT : 0; /* If the map is required, install it, and move on to the end of the extra data */ if (class_charcount > 0) { *code++ |= XCL_MAP; memcpy(code, class, 32); code = class_utf8data; } /* If the map is not required, slide down the extra data. */ else { int len = class_utf8data - (code + 33); memmove(code + 1, code + 33, len); code += len + 1; } /* Now fill in the complete length of the item */ PUT(previous, 1, code - previous); break; /* End of class handling */ } #endif /* If there are no characters > 255, negate the 32-byte map if necessary, and copy it into the code vector. If this is the first thing in the branch, there can be no first char setting, whatever the repeat count. Any reqbyte setting must remain unchanged after any kind of repeat. */ if (negate_class) { *code++ = OP_NCLASS; for (c = 0; c < 32; c++) code[c] = ~class[c]; } else { *code++ = OP_CLASS; memcpy(code, class, 32); } code += 32; break; /* Various kinds of repeat */ case '{': if (!is_counted_repeat(ptr+1)) goto NORMAL_CHAR; ptr = read_repeat_counts(ptr+1, &repeat_min, &repeat_max, errorptr); if (*errorptr != NULL) goto FAILED; goto REPEAT; case '*': repeat_min = 0; repeat_max = -1; goto REPEAT; case '+': repeat_min = 1; repeat_max = -1; goto REPEAT; case '?': repeat_min = 0; repeat_max = 1; REPEAT: if (previous == NULL) { *errorptr = ERR9; goto FAILED; } if (repeat_min == 0) { firstbyte = zerofirstbyte; /* Adjust for zero repeat */ reqbyte = zeroreqbyte; /* Ditto */ } /* Remember whether this is a variable length repeat */ reqvary = (repeat_min == repeat_max)? 0 : REQ_VARY; op_type = 0; /* Default single-char op codes */ possessive_quantifier = FALSE; /* Default not possessive quantifier */ /* Save start of previous item, in case we have to move it up to make space for an inserted OP_ONCE for the additional '+' extension. */ tempcode = previous; /* If the next character is '+', we have a possessive quantifier. This implies greediness, whatever the setting of the PCRE_UNGREEDY option. If the next character is '?' this is a minimizing repeat, by default, but if PCRE_UNGREEDY is set, it works the other way round. We change the repeat type to the non-default. */ if (ptr[1] == '+') { repeat_type = 0; /* Force greedy */ possessive_quantifier = TRUE; ptr++; } else if (ptr[1] == '?') { repeat_type = greedy_non_default; ptr++; } else repeat_type = greedy_default; /* If previous was a recursion, we need to wrap it inside brackets so that it can be replicated if necessary. */ if (*previous == OP_RECURSE) { memmove(previous + 1 + LINK_SIZE, previous, 1 + LINK_SIZE); code += 1 + LINK_SIZE; *previous = OP_BRA; PUT(previous, 1, code - previous); *code = OP_KET; PUT(code, 1, code - previous); code += 1 + LINK_SIZE; } /* If previous was a string of characters, chop off the last one and use it as the subject of the repeat. If there was only one character, we can abolish the previous item altogether. If a one-char item has a minumum of more than one, ensure that it is set in reqbyte - it might not be if a sequence such as x{3} is the first thing in a branch because the x will have gone into firstbyte instead. */ if (*previous == OP_CHARS) { /* Deal with UTF-8 characters that take up more than one byte. It's easier to write this out separately than try to macrify it. Use c to hold the length of the character in bytes, plus 0x80 to flag that it's a length rather than a small character. */ #ifdef SUPPORT_UTF8 if (utf8 && (code[-1] & 0x80) != 0) { uschar *lastchar = code - 1; while((*lastchar & 0xc0) == 0x80) lastchar--; c = code - lastchar; /* Length of UTF-8 character */ memcpy(utf8_char, lastchar, c); /* Save the char */ if (lastchar == previous + 2) /* There was only one character */ { code = previous; /* Abolish the previous item */ } else { previous[1] -= c; /* Adjust length of previous */ code = lastchar; /* Lost char off the end */ tempcode = code; /* Adjust position to be moved for '+' */ } c |= 0x80; /* Flag c as a length */ } else #endif /* Handle the case of a single byte - either with no UTF8 support, or with UTF-8 disabled, or for a UTF-8 character < 128. */ { c = *(--code); if (code == previous + 2) /* There was only one character */ { code = previous; /* Abolish the previous item */ if (repeat_min > 1) reqbyte = c | req_caseopt | cd->req_varyopt; } else { previous[1]--; /* adjust length */ tempcode = code; /* Adjust position to be moved for '+' */ } } goto OUTPUT_SINGLE_REPEAT; /* Code shared with single character types */ } /* If previous was a single negated character ([^a] or similar), we use one of the special opcodes, replacing it. The code is shared with single- character repeats by setting opt_type to add a suitable offset into repeat_type. OP_NOT is currently used only for single-byte chars. */ else if (*previous == OP_NOT) { op_type = OP_NOTSTAR - OP_STAR; /* Use "not" opcodes */ c = previous[1]; code = previous; goto OUTPUT_SINGLE_REPEAT; } /* If previous was a character type match (\d or similar), abolish it and create a suitable repeat item. The code is shared with single-character repeats by setting op_type to add a suitable offset into repeat_type. */ else if (*previous < OP_EODN) { op_type = OP_TYPESTAR - OP_STAR; /* Use type opcodes */ c = *previous; code = previous; OUTPUT_SINGLE_REPEAT: /* If the maximum is zero then the minimum must also be zero; Perl allows this case, so we do too - by simply omitting the item altogether. */ if (repeat_max == 0) goto END_REPEAT; /* Combine the op_type with the repeat_type */ repeat_type += op_type; /* A minimum of zero is handled either as the special case * or ?, or as an UPTO, with the maximum given. */ if (repeat_min == 0) { if (repeat_max == -1) *code++ = OP_STAR + repeat_type; else if (repeat_max == 1) *code++ = OP_QUERY + repeat_type; else { *code++ = OP_UPTO + repeat_type; PUT2INC(code, 0, repeat_max); } } /* The case {1,} is handled as the special case + */ else if (repeat_min == 1 && repeat_max == -1) *code++ = OP_PLUS + repeat_type; /* The case {n,n} is just an EXACT, while the general case {n,m} is handled as an EXACT followed by an UPTO. An EXACT of 1 is optimized. */ else { if (repeat_min != 1) { *code++ = OP_EXACT + op_type; /* NB EXACT doesn't have repeat_type */ PUT2INC(code, 0, repeat_min); } /* If the mininum is 1 and the previous item was a character string, we either have to put back the item that got cancelled if the string length was 1, or add the character back onto the end of a longer string. For a character type nothing need be done; it will just get put back naturally. Note that the final character is always going to get added below, so we leave code ready for its insertion. */ else if (*previous == OP_CHARS) { if (code == previous) code += 2; else /* In UTF-8 mode, a multibyte char has its length in c, with the 0x80 bit set as a flag. The length will always be between 2 and 6. */ #ifdef SUPPORT_UTF8 if (utf8 && c >= 128) previous[1] += c & 7; else #endif previous[1]++; } /* For a single negated character we also have to put back the item that got cancelled. At present this applies only to single byte characters in any mode. */ else if (*previous == OP_NOT) code++; /* If the maximum is unlimited, insert an OP_STAR. Before doing so, we have to insert the character for the previous code. In UTF-8 mode, long characters have their length in c, with the 0x80 bit as a flag. */ if (repeat_max < 0) { #ifdef SUPPORT_UTF8 if (utf8 && c >= 128) { memcpy(code, utf8_char, c & 7); code += c & 7; } else #endif *code++ = c; *code++ = OP_STAR + repeat_type; } /* Else insert an UPTO if the max is greater than the min, again preceded by the character, for the previously inserted code. */ else if (repeat_max != repeat_min) { #ifdef SUPPORT_UTF8 if (utf8 && c >= 128) { memcpy(code, utf8_char, c & 7); code += c & 7; } else #endif *code++ = c; repeat_max -= repeat_min; *code++ = OP_UPTO + repeat_type; PUT2INC(code, 0, repeat_max); } } /* The character or character type itself comes last in all cases. */ #ifdef SUPPORT_UTF8 if (utf8 && c >= 128) { memcpy(code, utf8_char, c & 7); code += c & 7; } else #endif *code++ = c; } /* If previous was a character class or a back reference, we put the repeat stuff after it, but just skip the item if the repeat was {0,0}. */ else if (*previous == OP_CLASS || *previous == OP_NCLASS || #ifdef SUPPORT_UTF8 *previous == OP_XCLASS || #endif *previous == OP_REF) { if (repeat_max == 0) { code = previous; goto END_REPEAT; } if (repeat_min == 0 && repeat_max == -1) *code++ = OP_CRSTAR + repeat_type; else if (repeat_min == 1 && repeat_max == -1) *code++ = OP_CRPLUS + repeat_type; else if (repeat_min == 0 && repeat_max == 1) *code++ = OP_CRQUERY + repeat_type; else { *code++ = OP_CRRANGE + repeat_type; PUT2INC(code, 0, repeat_min); if (repeat_max == -1) repeat_max = 0; /* 2-byte encoding for max */ PUT2INC(code, 0, repeat_max); } } /* If previous was a bracket group, we may have to replicate it in certain cases. */ else if (*previous >= OP_BRA || *previous == OP_ONCE || *previous == OP_COND) { register int i; int ketoffset = 0; int len = code - previous; uschar *bralink = NULL; /* If the maximum repeat count is unlimited, find the end of the bracket by scanning through from the start, and compute the offset back to it from the current code pointer. There may be an OP_OPT setting following the final KET, so we can't find the end just by going back from the code pointer. */ if (repeat_max == -1) { register uschar *ket = previous; do ket += GET(ket, 1); while (*ket != OP_KET); ketoffset = code - ket; } /* The case of a zero minimum is special because of the need to stick OP_BRAZERO in front of it, and because the group appears once in the data, whereas in other cases it appears the minimum number of times. For this reason, it is simplest to treat this case separately, as otherwise the code gets far too messy. There are several special subcases when the minimum is zero. */ if (repeat_min == 0) { /* If the maximum is also zero, we just omit the group from the output altogether. */ if (repeat_max == 0) { code = previous; goto END_REPEAT; } /* If the maximum is 1 or unlimited, we just have to stick in the BRAZERO and do no more at this point. However, we do need to adjust any OP_RECURSE calls inside the group that refer to the group itself or any internal group, because the offset is from the start of the whole regex. Temporarily terminate the pattern while doing this. */ if (repeat_max <= 1) { *code = OP_END; adjust_recurse(previous, 1, utf8, cd); memmove(previous+1, previous, len); code++; *previous++ = OP_BRAZERO + repeat_type; } /* If the maximum is greater than 1 and limited, we have to replicate in a nested fashion, sticking OP_BRAZERO before each set of brackets. The first one has to be handled carefully because it's the original copy, which has to be moved up. The remainder can be handled by code that is common with the non-zero minimum case below. We have to adjust the value or repeat_max, since one less copy is required. Once again, we may have to adjust any OP_RECURSE calls inside the group. */ else { int offset; *code = OP_END; adjust_recurse(previous, 2 + LINK_SIZE, utf8, cd); memmove(previous + 2 + LINK_SIZE, previous, len); code += 2 + LINK_SIZE; *previous++ = OP_BRAZERO + repeat_type; *previous++ = OP_BRA; /* We chain together the bracket offset fields that have to be filled in later when the ends of the brackets are reached. */ offset = (bralink == NULL)? 0 : previous - bralink; bralink = previous; PUTINC(previous, 0, offset); } repeat_max--; } /* If the minimum is greater than zero, replicate the group as many times as necessary, and adjust the maximum to the number of subsequent copies that we need. If we set a first char from the group, and didn't set a required char, copy the latter from the former. */ else { if (repeat_min > 1) { if (groupsetfirstbyte && reqbyte < 0) reqbyte = firstbyte; for (i = 1; i < repeat_min; i++) { memcpy(code, previous, len); code += len; } } if (repeat_max > 0) repeat_max -= repeat_min; } /* This code is common to both the zero and non-zero minimum cases. If the maximum is limited, it replicates the group in a nested fashion, remembering the bracket starts on a stack. In the case of a zero minimum, the first one was set up above. In all cases the repeat_max now specifies the number of additional copies needed. */ if (repeat_max >= 0) { for (i = repeat_max - 1; i >= 0; i--) { *code++ = OP_BRAZERO + repeat_type; /* All but the final copy start a new nesting, maintaining the chain of brackets outstanding. */ if (i != 0) { int offset; *code++ = OP_BRA; offset = (bralink == NULL)? 0 : code - bralink; bralink = code; PUTINC(code, 0, offset); } memcpy(code, previous, len); code += len; } /* Now chain through the pending brackets, and fill in their length fields (which are holding the chain links pro tem). */ while (bralink != NULL) { int oldlinkoffset; int offset = code - bralink + 1; uschar *bra = code - offset; oldlinkoffset = GET(bra, 1); bralink = (oldlinkoffset == 0)? NULL : bralink - oldlinkoffset; *code++ = OP_KET; PUTINC(code, 0, offset); PUT(bra, 1, offset); } } /* If the maximum is unlimited, set a repeater in the final copy. We can't just offset backwards from the current code point, because we don't know if there's been an options resetting after the ket. The correct offset was computed above. */ else code[-ketoffset] = OP_KETRMAX + repeat_type; } /* Else there's some kind of shambles */ else { *errorptr = ERR11; goto FAILED; } /* If the character following a repeat is '+', we wrap the entire repeated item inside OP_ONCE brackets. This is just syntactic sugar, taken from Sun's Java package. The repeated item starts at tempcode, not at previous, which might be the first part of a string whose (former) last char we repeated. However, we don't support '+' after a greediness '?'. */ if (possessive_quantifier) { int len = code - tempcode; memmove(tempcode + 1+LINK_SIZE, tempcode, len); code += 1 + LINK_SIZE; len += 1 + LINK_SIZE; tempcode[0] = OP_ONCE; *code++ = OP_KET; PUTINC(code, 0, len); PUT(tempcode, 1, len); } /* In all case we no longer have a previous item. We also set the "follows varying string" flag for subsequently encountered reqbytes if it isn't already set and we have just passed a varying length item. */ END_REPEAT: previous = NULL; cd->req_varyopt |= reqvary; break; /* Start of nested bracket sub-expression, or comment or lookahead or lookbehind or option setting or condition. First deal with special things that can come after a bracket; all are introduced by ?, and the appearance of any of them means that this is not a referencing group. They were checked for validity in the first pass over the string, so we don't have to check for syntax errors here. */ case '(': newoptions = options; skipbytes = 0; if (*(++ptr) == '?') { int set, unset; int *optset; switch (*(++ptr)) { case '#': /* Comment; skip to ket */ ptr++; while (*ptr != ')') ptr++; continue; case ':': /* Non-extracting bracket */ bravalue = OP_BRA; ptr++; break; case '(': bravalue = OP_COND; /* Conditional group */ /* Condition to test for recursion */ if (ptr[1] == 'R') { code[1+LINK_SIZE] = OP_CREF; PUT2(code, 2+LINK_SIZE, CREF_RECURSE); skipbytes = 3; ptr += 3; } /* Condition to test for a numbered subpattern match. We know that if a digit follows ( then there will just be digits until ) because the syntax was checked in the first pass. */ else if ((digitab[ptr[1]] && ctype_digit) != 0) { int condref; /* Don't amalgamate; some compilers */ condref = *(++ptr) - '0'; /* grumble at autoincrement in declaration */ while (*(++ptr) != ')') condref = condref*10 + *ptr - '0'; if (condref == 0) { *errorptr = ERR35; goto FAILED; } ptr++; code[1+LINK_SIZE] = OP_CREF; PUT2(code, 2+LINK_SIZE, condref); skipbytes = 3; } /* For conditions that are assertions, we just fall through, having set bravalue above. */ break; case '=': /* Positive lookahead */ bravalue = OP_ASSERT; ptr++; break; case '!': /* Negative lookahead */ bravalue = OP_ASSERT_NOT; ptr++; break; case '<': /* Lookbehinds */ switch (*(++ptr)) { case '=': /* Positive lookbehind */ bravalue = OP_ASSERTBACK; ptr++; break; case '!': /* Negative lookbehind */ bravalue = OP_ASSERTBACK_NOT; ptr++; break; } break; case '>': /* One-time brackets */ bravalue = OP_ONCE; ptr++; break; case 'C': /* Callout - may be followed by digits */ *code++ = OP_CALLOUT; { int n = 0; while ((digitab[*(++ptr)] & ctype_digit) != 0) n = n * 10 + *ptr - '0'; if (n > 255) { *errorptr = ERR38; goto FAILED; } *code++ = n; } previous = NULL; continue; case 'P': /* Named subpattern handling */ if (*(++ptr) == '<') /* Definition */ { int i, namelen; uschar *slot = cd->name_table; const uschar *name; /* Don't amalgamate; some compilers */ name = ++ptr; /* grumble at autoincrement in declaration */ while (*ptr++ != '>'); namelen = ptr - name - 1; for (i = 0; i < cd->names_found; i++) { int crc = memcmp(name, slot+2, namelen); if (crc == 0) { if (slot[2+namelen] == 0) { *errorptr = ERR43; goto FAILED; } crc = -1; /* Current name is substring */ } if (crc < 0) { memmove(slot + cd->name_entry_size, slot, (cd->names_found - i) * cd->name_entry_size); break; } slot += cd->name_entry_size; } PUT2(slot, 0, *brackets + 1); memcpy(slot + 2, name, namelen); slot[2+namelen] = 0; cd->names_found++; goto NUMBERED_GROUP; } if (*ptr == '=' || *ptr == '>') /* Reference or recursion */ { int i, namelen; int type = *ptr++; const uschar *name = ptr; uschar *slot = cd->name_table; while (*ptr != ')') ptr++; namelen = ptr - name; for (i = 0; i < cd->names_found; i++) { if (strncmp((char *)name, (char *)slot+2, namelen) == 0) break; slot += cd->name_entry_size; } if (i >= cd->names_found) { *errorptr = ERR15; goto FAILED; } recno = GET2(slot, 0); if (type == '>') goto HANDLE_RECURSION; /* A few lines below */ /* Back reference */ previous = code; *code++ = OP_REF; PUT2INC(code, 0, recno); cd->backref_map |= (recno < 32)? (1 << recno) : 1; if (recno > cd->top_backref) cd->top_backref = recno; continue; } /* Should never happen */ break; case 'R': /* Pattern recursion */ ptr++; /* Same as (?0) */ /* Fall through */ /* Recursion or "subroutine" call */ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { const uschar *called; recno = 0; while((digitab[*ptr] & ctype_digit) != 0) recno = recno * 10 + *ptr++ - '0'; /* Come here from code above that handles a named recursion */ HANDLE_RECURSION: previous = code; /* Find the bracket that is being referenced. Temporarily end the regex in case it doesn't exist. */ *code = OP_END; called = (recno == 0)? cd->start_code : find_bracket(cd->start_code, utf8, recno); if (called == NULL) { *errorptr = ERR15; goto FAILED; } /* If the subpattern is still open, this is a recursive call. We check to see if this is a left recursion that could loop for ever, and diagnose that case. */ if (GET(called, 1) == 0 && could_be_empty(called, code, bcptr, utf8)) { *errorptr = ERR40; goto FAILED; } /* Insert the recursion/subroutine item */ *code = OP_RECURSE; PUT(code, 1, called - cd->start_code); code += 1 + LINK_SIZE; } continue; /* Character after (? not specially recognized */ default: /* Option setting */ set = unset = 0; optset = &set; while (*ptr != ')' && *ptr != ':') { switch (*ptr++) { case '-': optset = &unset; break; case 'i': *optset |= PCRE_CASELESS; break; case 'm': *optset |= PCRE_MULTILINE; break; case 's': *optset |= PCRE_DOTALL; break; case 'x': *optset |= PCRE_EXTENDED; break; case 'U': *optset |= PCRE_UNGREEDY; break; case 'X': *optset |= PCRE_EXTRA; break; } } /* Set up the changed option bits, but don't change anything yet. */ newoptions = (options | set) & (~unset); /* If the options ended with ')' this is not the start of a nested group with option changes, so the options change at this level. Compile code to change the ims options if this setting actually changes any of them. We also pass the new setting back so that it can be put at the start of any following branches, and when this group ends (if we are in a group), a resetting item can be compiled. Note that if this item is right at the start of the pattern, the options will have been abstracted and made global, so there will be no change to compile. */ if (*ptr == ')') { if ((options & PCRE_IMS) != (newoptions & PCRE_IMS)) { *code++ = OP_OPT; *code++ = newoptions & PCRE_IMS; } /* Change options at this level, and pass them back for use in subsequent branches. Reset the greedy defaults and the case value for firstbyte and reqbyte. */ *optionsptr = options = newoptions; greedy_default = ((newoptions & PCRE_UNGREEDY) != 0); greedy_non_default = greedy_default ^ 1; req_caseopt = ((options & PCRE_CASELESS) != 0)? REQ_CASELESS : 0; previous = NULL; /* This item can't be repeated */ continue; /* It is complete */ } /* If the options ended with ':' we are heading into a nested group with possible change of options. Such groups are non-capturing and are not assertions of any kind. All we need to do is skip over the ':'; the newoptions value is handled below. */ bravalue = OP_BRA; ptr++; } } /* If PCRE_NO_AUTO_CAPTURE is set, all unadorned brackets become non-capturing and behave like (?:...) brackets */ else if ((options & PCRE_NO_AUTO_CAPTURE) != 0) { bravalue = OP_BRA; } /* Else we have a referencing group; adjust the opcode. If the bracket number is greater than EXTRACT_BASIC_MAX, we set the opcode one higher, and arrange for the true number to follow later, in an OP_BRANUMBER item. */ else { NUMBERED_GROUP: if (++(*brackets) > EXTRACT_BASIC_MAX) { bravalue = OP_BRA + EXTRACT_BASIC_MAX + 1; code[1+LINK_SIZE] = OP_BRANUMBER; PUT2(code, 2+LINK_SIZE, *brackets); skipbytes = 3; } else bravalue = OP_BRA + *brackets; } /* Process nested bracketed re. Assertions may not be repeated, but other kinds can be. We copy code into a non-register variable in order to be able to pass its address because some compilers complain otherwise. Pass in a new setting for the ims options if they have changed. */ previous = (bravalue >= OP_ONCE)? code : NULL; *code = bravalue; tempcode = code; tempreqvary = cd->req_varyopt; /* Save value before bracket */ if (!compile_regex( newoptions, /* The complete new option state */ options & PCRE_IMS, /* The previous ims option state */ brackets, /* Extracting bracket count */ &tempcode, /* Where to put code (updated) */ &ptr, /* Input pointer (updated) */ errorptr, /* Where to put an error message */ (bravalue == OP_ASSERTBACK || bravalue == OP_ASSERTBACK_NOT), /* TRUE if back assert */ skipbytes, /* Skip over OP_COND/OP_BRANUMBER */ &subfirstbyte, /* For possible first char */ &subreqbyte, /* For possible last char */ bcptr, /* Current branch chain */ cd)) /* Tables block */ goto FAILED; /* At the end of compiling, code is still pointing to the start of the group, while tempcode has been updated to point past the end of the group and any option resetting that may follow it. The pattern pointer (ptr) is on the bracket. */ /* If this is a conditional bracket, check that there are no more than two branches in the group. */ else if (bravalue == OP_COND) { uschar *tc = code; condcount = 0; do { condcount++; tc += GET(tc,1); } while (*tc != OP_KET); if (condcount > 2) { *errorptr = ERR27; goto FAILED; } /* If there is just one branch, we must not make use of its firstbyte or reqbyte, because this is equivalent to an empty second branch. */ if (condcount == 1) subfirstbyte = subreqbyte = REQ_NONE; } /* Handle updating of the required and first characters. Update for normal brackets of all kinds, and conditions with two branches (see code above). If the bracket is followed by a quantifier with zero repeat, we have to back off. Hence the definition of zeroreqbyte and zerofirstbyte outside the main loop so that they can be accessed for the back off. */ zeroreqbyte = reqbyte; zerofirstbyte = firstbyte; groupsetfirstbyte = FALSE; if (bravalue >= OP_BRA || bravalue == OP_ONCE || bravalue == OP_COND) { /* If we have not yet set a firstbyte in this branch, take it from the subpattern, remembering that it was set here so that a repeat of more than one can replicate it as reqbyte if necessary. If the subpattern has no firstbyte, set "none" for the whole branch. In both cases, a zero repeat forces firstbyte to "none". */ if (firstbyte == REQ_UNSET) { if (subfirstbyte >= 0) { firstbyte = subfirstbyte; groupsetfirstbyte = TRUE; } else firstbyte = REQ_NONE; zerofirstbyte = REQ_NONE; } /* If firstbyte was previously set, convert the subpattern's firstbyte into reqbyte if there wasn't one, using the vary flag that was in existence beforehand. */ else if (subfirstbyte >= 0 && subreqbyte < 0) subreqbyte = subfirstbyte | tempreqvary; /* If the subpattern set a required byte (or set a first byte that isn't really the first byte - see above), set it. */ if (subreqbyte >= 0) reqbyte = subreqbyte; } /* For a forward assertion, we take the reqbyte, if set. This can be helpful if the pattern that follows the assertion doesn't set a different char. For example, it's useful for /(?=abcde).+/. We can't set firstbyte for an assertion, however because it leads to incorrect effect for patterns such as /(?=a)a.+/ when the "real" "a" would then become a reqbyte instead of a firstbyte. This is overcome by a scan at the end if there's no firstbyte, looking for an asserted first char. */ else if (bravalue == OP_ASSERT && subreqbyte >= 0) reqbyte = subreqbyte; /* Now update the main code pointer to the end of the group. */ code = tempcode; /* Error if hit end of pattern */ if (*ptr != ')') { *errorptr = ERR14; goto FAILED; } break; /* Check \ for being a real metacharacter; if not, fall through and handle it as a data character at the start of a string. Escape items are checked for validity in the pre-compiling pass. */ case '\\': tempptr = ptr; c = check_escape(&ptr, errorptr, *brackets, options, FALSE); /* Handle metacharacters introduced by \. For ones like \d, the ESC_ values are arranged to be the negation of the corresponding OP_values. For the back references, the values are ESC_REF plus the reference number. Only back references and those types that consume a character may be repeated. We can test for values between ESC_b and ESC_Z for the latter; this may have to change if any new ones are ever created. */ if (c < 0) { if (-c == ESC_Q) /* Handle start of quoted string */ { if (ptr[1] == '\\' && ptr[2] == 'E') ptr += 2; /* avoid empty string */ else inescq = TRUE; continue; } /* For metasequences that actually match a character, we disable the setting of a first character if it hasn't already been set. */ if (firstbyte == REQ_UNSET && -c > ESC_b && -c < ESC_Z) firstbyte = REQ_NONE; /* Set values to reset to if this is followed by a zero repeat. */ zerofirstbyte = firstbyte; zeroreqbyte = reqbyte; /* Back references are handled specially */ if (-c >= ESC_REF) { int number = -c - ESC_REF; previous = code; *code++ = OP_REF; PUT2INC(code, 0, number); } else { previous = (-c > ESC_b && -c < ESC_Z)? code : NULL; *code++ = -c; } continue; } /* Data character: reset and fall through */ ptr = tempptr; c = '\\'; /* Handle a run of data characters until a metacharacter is encountered. The first character is guaranteed not to be whitespace or # when the extended flag is set. */ NORMAL_CHAR: default: previous = code; *code = OP_CHARS; code += 2; length = 0; do { /* If in \Q...\E, check for the end; if not, we always have a literal */ if (inescq) { if (c == '\\' && ptr[1] == 'E') { inescq = FALSE; ptr++; } else { *code++ = c; length++; } continue; } /* Skip white space and comments for /x patterns */ if ((options & PCRE_EXTENDED) != 0) { if ((cd->ctypes[c] & ctype_space) != 0) continue; if (c == '#') { /* The space before the ; is to avoid a warning on a silly compiler on the Macintosh. */ while ((c = *(++ptr)) != 0 && c != NEWLINE) ; if (c == 0) break; continue; } } /* Backslash may introduce a data char or a metacharacter. Escaped items are checked for validity in the pre-compiling pass. Stop the string before a metaitem. */ if (c == '\\') { tempptr = ptr; c = check_escape(&ptr, errorptr, *brackets, options, FALSE); if (c < 0) { ptr = tempptr; break; } /* If a character is > 127 in UTF-8 mode, we have to turn it into two or more bytes in the UTF-8 encoding. */ #ifdef SUPPORT_UTF8 if (utf8 && c > 127) { uschar buffer[8]; int len = ord2utf8(c, buffer); for (c = 0; c < len; c++) *code++ = buffer[c]; length += len; continue; } #endif } /* Ordinary character or single-char escape */ *code++ = c; length++; } /* This "while" is the end of the "do" above. */ while (length < MAXLIT && (cd->ctypes[c = *(++ptr)] & ctype_meta) == 0); /* Update the first and last requirements. These are always bytes, even in UTF-8 mode. However, there is a special case to be considered when there are only one or two characters. Because this gets messy in UTF-8 mode, the code is kept separate. When we get here "length" contains the number of bytes. */ #ifdef SUPPORT_UTF8 if (utf8 && length > 1) { uschar *t = previous + 3; /* After this code, t */ while (t < code && (*t & 0xc0) == 0x80) t++; /* follows the 1st char */ /* Handle the case when there is only one multibyte character. It must have at least two bytes because of the "length > 1" test above. */ if (t == code) { /* If no previous first byte, set it from this character, but revert to none on a zero repeat. */ if (firstbyte == REQ_UNSET) { zerofirstbyte = REQ_NONE; firstbyte = previous[2]; } /* Otherwise, leave the first byte value alone, and don't change it on a zero repeat */ else zerofirstbyte = firstbyte; /* In both cases, a zero repeat resets the previous required byte */ zeroreqbyte = reqbyte; } /* Handle the case when there is more than one character. These may be single-byte or multibyte characters */ else { t = code - 1; /* After this code, t is at the */ while ((*t & 0xc0) == 0x80) t--; /* start of the last character */ /* If no previous first byte, set it from the first character, and retain it on a zero repeat (of the last character). The required byte is reset on a zero repeat, either to the byte before the last character, unless this is the first byte of the string. In that case, it reverts to its previous value. */ if (firstbyte == REQ_UNSET) { zerofirstbyte = firstbyte = previous[2] | req_caseopt; zeroreqbyte = (t - 1 == previous + 2)? reqbyte : t[-1] | req_caseopt | cd->req_varyopt; } /* If there was a previous first byte, leave it alone, and don't change it on a zero repeat. The required byte is reset on a zero repeat to the byte before the last character. */ else { zerofirstbyte = firstbyte; zeroreqbyte = t[-1] | req_caseopt | cd->req_varyopt; } } /* In all cases (we know length > 1), the new required byte is the last byte of the string. */ reqbyte = code[-1] | req_caseopt | cd->req_varyopt; } else /* End of UTF-8 coding */ #endif /* This is the code for non-UTF-8 operation, either without UTF-8 support, or when UTF-8 is not enabled. */ { /* firstbyte was not previously set; take it from this string */ if (firstbyte == REQ_UNSET) { if (length == 1) { zerofirstbyte = REQ_NONE; firstbyte = previous[2] | req_caseopt; zeroreqbyte = reqbyte; } else { zerofirstbyte = firstbyte = previous[2] | req_caseopt; zeroreqbyte = (length > 2)? (code[-2] | req_caseopt | cd->req_varyopt) : reqbyte; reqbyte = code[-1] | req_caseopt | cd->req_varyopt; } } /* firstbyte was previously set */ else { zerofirstbyte = firstbyte; zeroreqbyte = (length == 1)? reqbyte : code[-2] | req_caseopt | cd->req_varyopt; reqbyte = code[-1] | req_caseopt | cd->req_varyopt; } } /* Set the length in the data vector, and advance to the next state. */ previous[1] = length; if (length < MAXLIT) ptr--; break; } } /* end of big loop */ /* Control never reaches here by falling through, only by a goto for all the error states. Pass back the position in the pattern so that it can be displayed to the user for diagnosing the error. */ FAILED: *ptrptr = ptr; return FALSE; } /************************************************* * Compile sequence of alternatives * *************************************************/ /* On entry, ptr is pointing past the bracket character, but on return it points to the closing bracket, or vertical bar, or end of string. The code variable is pointing at the byte into which the BRA operator has been stored. If the ims options are changed at the start (for a (?ims: group) or during any branch, we need to insert an OP_OPT item at the start of every following branch to ensure they get set correctly at run time, and also pass the new options into every subsequent branch compile. Argument: options option bits, including any changes for this subpattern oldims previous settings of ims option bits brackets -> int containing the number of extracting brackets used codeptr -> the address of the current code pointer ptrptr -> the address of the current pattern pointer errorptr -> pointer to error message lookbehind TRUE if this is a lookbehind assertion skipbytes skip this many bytes at start (for OP_COND, OP_BRANUMBER) firstbyteptr place to put the first required character, or a negative number reqbyteptr place to put the last required character, or a negative number bcptr pointer to the chain of currently open branches cd points to the data block with tables pointers etc. Returns: TRUE on success */ static BOOL compile_regex(int options, int oldims, int *brackets, uschar **codeptr, const uschar **ptrptr, const char **errorptr, BOOL lookbehind, int skipbytes, int *firstbyteptr, int *reqbyteptr, branch_chain *bcptr, compile_data *cd) { const uschar *ptr = *ptrptr; uschar *code = *codeptr; uschar *last_branch = code; uschar *start_bracket = code; uschar *reverse_count = NULL; int firstbyte, reqbyte; int branchfirstbyte, branchreqbyte; branch_chain bc; bc.outer = bcptr; bc.current = code; firstbyte = reqbyte = REQ_UNSET; /* Offset is set zero to mark that this bracket is still open */ PUT(code, 1, 0); code += 1 + LINK_SIZE + skipbytes; /* Loop for each alternative branch */ for (;;) { /* Handle a change of ims options at the start of the branch */ if ((options & PCRE_IMS) != oldims) { *code++ = OP_OPT; *code++ = options & PCRE_IMS; } /* Set up dummy OP_REVERSE if lookbehind assertion */ if (lookbehind) { *code++ = OP_REVERSE; reverse_count = code; PUTINC(code, 0, 0); } /* Now compile the branch */ if (!compile_branch(&options, brackets, &code, &ptr, errorptr, &branchfirstbyte, &branchreqbyte, &bc, cd)) { *ptrptr = ptr; return FALSE; } /* If this is the first branch, the firstbyte and reqbyte values for the branch become the values for the regex. */ if (*last_branch != OP_ALT) { firstbyte = branchfirstbyte; reqbyte = branchreqbyte; } /* If this is not the first branch, the first char and reqbyte have to match the values from all the previous branches, except that if the previous value for reqbyte didn't have REQ_VARY set, it can still match, and we set REQ_VARY for the regex. */ else { /* If we previously had a firstbyte, but it doesn't match the new branch, we have to abandon the firstbyte for the regex, but if there was previously no reqbyte, it takes on the value of the old firstbyte. */ if (firstbyte >= 0 && firstbyte != branchfirstbyte) { if (reqbyte < 0) reqbyte = firstbyte; firstbyte = REQ_NONE; } /* If we (now or from before) have no firstbyte, a firstbyte from the branch becomes a reqbyte if there isn't a branch reqbyte. */ if (firstbyte < 0 && branchfirstbyte >= 0 && branchreqbyte < 0) branchreqbyte = branchfirstbyte; /* Now ensure that the reqbytes match */ if ((reqbyte & ~REQ_VARY) != (branchreqbyte & ~REQ_VARY)) reqbyte = REQ_NONE; else reqbyte |= branchreqbyte; /* To "or" REQ_VARY */ } /* If lookbehind, check that this branch matches a fixed-length string, and put the length into the OP_REVERSE item. Temporarily mark the end of the branch with OP_END. */ if (lookbehind) { int length; *code = OP_END; length = find_fixedlength(last_branch, options); DPRINTF(("fixed length = %d\n", length)); if (length < 0) { *errorptr = (length == -2)? ERR36 : ERR25; *ptrptr = ptr; return FALSE; } PUT(reverse_count, 0, length); } /* Reached end of expression, either ')' or end of pattern. Go back through the alternative branches and reverse the chain of offsets, with the field in the BRA item now becoming an offset to the first alternative. If there are no alternatives, it points to the end of the group. The length in the terminating ket is always the length of the whole bracketed item. If any of the ims options were changed inside the group, compile a resetting op-code following, except at the very end of the pattern. Return leaving the pointer at the terminating char. */ if (*ptr != '|') { int length = code - last_branch; do { int prev_length = GET(last_branch, 1); PUT(last_branch, 1, length); length = prev_length; last_branch -= length; } while (length > 0); /* Fill in the ket */ *code = OP_KET; PUT(code, 1, code - start_bracket); code += 1 + LINK_SIZE; /* Resetting option if needed */ if ((options & PCRE_IMS) != oldims && *ptr == ')') { *code++ = OP_OPT; *code++ = oldims; } /* Set values to pass back */ *codeptr = code; *ptrptr = ptr; *firstbyteptr = firstbyte; *reqbyteptr = reqbyte; return TRUE; } /* Another branch follows; insert an "or" node. Its length field points back to the previous branch while the bracket remains open. At the end the chain is reversed. It's done like this so that the start of the bracket has a zero offset until it is closed, making it possible to detect recursion. */ *code = OP_ALT; PUT(code, 1, code - last_branch); bc.current = last_branch = code; code += 1 + LINK_SIZE; ptr++; } /* Control never reaches here */ } /************************************************* * Check for anchored expression * *************************************************/ /* Try to find out if this is an anchored regular expression. Consider each alternative branch. If they all start with OP_SOD or OP_CIRC, or with a bracket all of whose alternatives start with OP_SOD or OP_CIRC (recurse ad lib), then it's anchored. However, if this is a multiline pattern, then only OP_SOD counts, since OP_CIRC can match in the middle. We can also consider a regex to be anchored if OP_SOM starts all its branches. This is the code for \G, which means "match at start of match position, taking into account the match offset". A branch is also implicitly anchored if it starts with .* and DOTALL is set, because that will try the rest of the pattern at all possible matching points, so there is no point trying again.... er .... .... except when the .* appears inside capturing parentheses, and there is a subsequent back reference to those parentheses. We haven't enough information to catch that case precisely. At first, the best we could do was to detect when .* was in capturing brackets and the highest back reference was greater than or equal to that level. However, by keeping a bitmap of the first 31 back references, we can catch some of the more common cases more precisely. Arguments: code points to start of expression (the bracket) options points to the options setting bracket_map a bitmap of which brackets we are inside while testing; this handles up to substring 31; after that we just have to take the less precise approach backref_map the back reference bitmap Returns: TRUE or FALSE */ static BOOL is_anchored(register const uschar *code, int *options, unsigned int bracket_map, unsigned int backref_map) { do { const uschar *scode = first_significant_code(code + 1+LINK_SIZE, options, PCRE_MULTILINE); register int op = *scode; /* Capturing brackets */ if (op > OP_BRA) { int new_map; op -= OP_BRA; if (op > EXTRACT_BASIC_MAX) op = GET2(scode, 2+LINK_SIZE); new_map = bracket_map | ((op < 32)? (1 << op) : 1); if (!is_anchored(scode, options, new_map, backref_map)) return FALSE; } /* Other brackets */ else if (op == OP_BRA || op == OP_ASSERT || op == OP_ONCE || op == OP_COND) { if (!is_anchored(scode, options, bracket_map, backref_map)) return FALSE; } /* .* is not anchored unless DOTALL is set and it isn't in brackets that are or may be referenced. */ else if ((op == OP_TYPESTAR || op == OP_TYPEMINSTAR) && (*options & PCRE_DOTALL) != 0) { if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE; } /* Check for explicit anchoring */ else if (op != OP_SOD && op != OP_SOM && ((*options & PCRE_MULTILINE) != 0 || op != OP_CIRC)) return FALSE; code += GET(code, 1); } while (*code == OP_ALT); /* Loop for each alternative */ return TRUE; } /************************************************* * Check for starting with ^ or .* * *************************************************/ /* This is called to find out if every branch starts with ^ or .* so that "first char" processing can be done to speed things up in multiline matching and for non-DOTALL patterns that start with .* (which must start at the beginning or after \n). As in the case of is_anchored() (see above), we have to take account of back references to capturing brackets that contain .* because in that case we can't make the assumption. Arguments: code points to start of expression (the bracket) bracket_map a bitmap of which brackets we are inside while testing; this handles up to substring 31; after that we just have to take the less precise approach backref_map the back reference bitmap Returns: TRUE or FALSE */ static BOOL is_startline(const uschar *code, unsigned int bracket_map, unsigned int backref_map) { do { const uschar *scode = first_significant_code(code + 1+LINK_SIZE, NULL, 0); register int op = *scode; /* Capturing brackets */ if (op > OP_BRA) { int new_map; op -= OP_BRA; if (op > EXTRACT_BASIC_MAX) op = GET2(scode, 2+LINK_SIZE); new_map = bracket_map | ((op < 32)? (1 << op) : 1); if (!is_startline(scode, new_map, backref_map)) return FALSE; } /* Other brackets */ else if (op == OP_BRA || op == OP_ASSERT || op == OP_ONCE || op == OP_COND) { if (!is_startline(scode, bracket_map, backref_map)) return FALSE; } /* .* is not anchored unless DOTALL is set and it isn't in brackets that may be referenced. */ else if (op == OP_TYPESTAR || op == OP_TYPEMINSTAR) { if (scode[1] != OP_ANY || (bracket_map & backref_map) != 0) return FALSE; } /* Check for explicit circumflex */ else if (op != OP_CIRC) return FALSE; code += GET(code, 1); } while (*code == OP_ALT); /* Loop for each alternative */ return TRUE; } /************************************************* * Check for asserted fixed first char * *************************************************/ /* During compilation, the "first char" settings from forward assertions are discarded, because they can cause conflicts with actual literals that follow. However, if we end up without a first char setting for an unanchored pattern, it is worth scanning the regex to see if there is an initial asserted first char. If all branches start with the same asserted char, or with a bracket all of whose alternatives start with the same asserted char (recurse ad lib), then we return that char, otherwise -1. Arguments: code points to start of expression (the bracket) options pointer to the options (used to check casing changes) inassert TRUE if in an assertion Returns: -1 or the fixed first char */ static int find_firstassertedchar(const uschar *code, int *options, BOOL inassert) { register int c = -1; do { int d; const uschar *scode = first_significant_code(code + 1+LINK_SIZE, options, PCRE_CASELESS); register int op = *scode; if (op >= OP_BRA) op = OP_BRA; switch(op) { default: return -1; case OP_BRA: case OP_ASSERT: case OP_ONCE: case OP_COND: if ((d = find_firstassertedchar(scode, options, op == OP_ASSERT)) < 0) return -1; if (c < 0) c = d; else if (c != d) return -1; break; case OP_EXACT: /* Fall through */ scode++; case OP_CHARS: /* Fall through */ scode++; case OP_PLUS: case OP_MINPLUS: if (!inassert) return -1; if (c < 0) { c = scode[1]; if ((*options & PCRE_CASELESS) != 0) c |= REQ_CASELESS; } else if (c != scode[1]) return -1; break; } code += GET(code, 1); } while (*code == OP_ALT); return c; } #ifdef SUPPORT_UTF8 /************************************************* * Validate a UTF-8 string * *************************************************/ /* This function is called (optionally) at the start of compile or match, to validate that a supposed UTF-8 string is actually valid. The early check means that subsequent code can assume it is dealing with a valid string. The check can be turned off for maximum performance, but then consequences of supplying an invalid string are then undefined. Arguments: string points to the string length length of string, or -1 if the string is zero-terminated Returns: < 0 if the string is a valid UTF-8 string >= 0 otherwise; the value is the offset of the bad byte */ static int valid_utf8(const uschar *string, int length) { register const uschar *p; if (length < 0) { for (p = string; *p != 0; p++); length = p - string; } for (p = string; length-- > 0; p++) { register int ab; register int c = *p; if (c < 128) continue; if ((c & 0xc0) != 0xc0) return p - string; ab = utf8_table4[c & 0x3f]; /* Number of additional bytes */ if (length < ab) return p - string; length -= ab; /* Check top bits in the second byte */ if ((*(++p) & 0xc0) != 0x80) return p - string; /* Check for overlong sequences for each different length */ switch (ab) { /* Check for xx00 000x */ case 1: if ((c & 0x3e) == 0) return p - string; continue; /* We know there aren't any more bytes to check */ /* Check for 1110 0000, xx0x xxxx */ case 2: if (c == 0xe0 && (*p & 0x20) == 0) return p - string; break; /* Check for 1111 0000, xx00 xxxx */ case 3: if (c == 0xf0 && (*p & 0x30) == 0) return p - string; break; /* Check for 1111 1000, xx00 0xxx */ case 4: if (c == 0xf8 && (*p & 0x38) == 0) return p - string; break; /* Check for leading 0xfe or 0xff, and then for 1111 1100, xx00 00xx */ case 5: if (c == 0xfe || c == 0xff || (c == 0xfc && (*p & 0x3c) == 0)) return p - string; break; } /* Check for valid bytes after the 2nd, if any; all must start 10 */ while (--ab > 0) { if ((*(++p) & 0xc0) != 0x80) return p - string; } } return -1; } #endif /************************************************* * Compile a Regular Expression * *************************************************/ /* This function takes a string and returns a pointer to a block of store holding a compiled version of the expression. Arguments: pattern the regular expression options various option bits errorptr pointer to pointer to error text erroroffset ptr offset in pattern where error was detected tables pointer to character tables or NULL Returns: pointer to compiled data block, or NULL on error, with errorptr and erroroffset set */ EXPORT pcre * pcre_compile(const char *pattern, int options, const char **errorptr, int *erroroffset, const unsigned char *tables) { real_pcre *re; int length = 1 + LINK_SIZE; /* For initial BRA plus length */ int runlength; int c, firstbyte, reqbyte; int bracount = 0; int branch_extra = 0; int branch_newextra; int item_count = -1; int name_count = 0; int max_name_size = 0; #ifdef SUPPORT_UTF8 int lastcharlength = 0; BOOL utf8; BOOL class_utf8; #endif BOOL inescq = FALSE; unsigned int brastackptr = 0; size_t size; uschar *code; const uschar *codestart; const uschar *ptr; compile_data compile_block; int brastack[BRASTACK_SIZE]; uschar bralenstack[BRASTACK_SIZE]; /* We can't pass back an error message if errorptr is NULL; I guess the best we can do is just return NULL. */ if (errorptr == NULL) return NULL; *errorptr = NULL; /* However, we can give a message for this error */ if (erroroffset == NULL) { *errorptr = ERR16; return NULL; } *erroroffset = 0; /* Can't support UTF8 unless PCRE has been compiled to include the code. */ #ifdef SUPPORT_UTF8 utf8 = (options & PCRE_UTF8) != 0; if (utf8 && (options & PCRE_NO_UTF8_CHECK) == 0 && (*erroroffset = valid_utf8((uschar *)pattern, -1)) >= 0) { *errorptr = ERR44; return NULL; } #else if ((options & PCRE_UTF8) != 0) { *errorptr = ERR32; return NULL; } #endif if ((options & ~PUBLIC_OPTIONS) != 0) { *errorptr = ERR17; return NULL; } /* Set up pointers to the individual character tables */ if (tables == NULL) tables = pcre_default_tables; compile_block.lcc = tables + lcc_offset; compile_block.fcc = tables + fcc_offset; compile_block.cbits = tables + cbits_offset; compile_block.ctypes = tables + ctypes_offset; /* Maximum back reference and backref bitmap. This is updated for numeric references during the first pass, but for named references during the actual compile pass. The bitmap records up to 31 back references to help in deciding whether (.*) can be treated as anchored or not. */ compile_block.top_backref = 0; compile_block.backref_map = 0; /* Reflect pattern for debugging output */ DPRINTF(("------------------------------------------------------------------\n")); DPRINTF(("%s\n", pattern)); /* The first thing to do is to make a pass over the pattern to compute the amount of store required to hold the compiled code. This does not have to be perfect as long as errors are overestimates. At the same time we can detect any flag settings right at the start, and extract them. Make an attempt to correct for any counted white space if an "extended" flag setting appears late in the pattern. We can't be so clever for #-comments. */ ptr = (const uschar *)(pattern - 1); while ((c = *(++ptr)) != 0) { int min, max; int class_optcount; int bracket_length; int duplength; /* If we are inside a \Q...\E sequence, all chars are literal */ if (inescq) goto NORMAL_CHAR; /* Otherwise, first check for ignored whitespace and comments */ if ((options & PCRE_EXTENDED) != 0) { if ((compile_block.ctypes[c] & ctype_space) != 0) continue; if (c == '#') { /* The space before the ; is to avoid a warning on a silly compiler on the Macintosh. */ while ((c = *(++ptr)) != 0 && c != NEWLINE) ; if (c == 0) break; continue; } } item_count++; /* Is zero for the first non-comment item */ switch(c) { /* A backslashed item may be an escaped "normal" character or a character type. For a "normal" character, put the pointers and character back so that tests for whitespace etc. in the input are done correctly. */ case '\\': { const uschar *save_ptr = ptr; c = check_escape(&ptr, errorptr, bracount, options, FALSE); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; if (c >= 0) { ptr = save_ptr; c = '\\'; goto NORMAL_CHAR; } } /* If \Q, enter "literal" mode */ if (-c == ESC_Q) { inescq = TRUE; continue; } /* Other escapes need one byte, and are of length one for repeats */ length++; #ifdef SUPPORT_UTF8 lastcharlength = 1; #endif /* A back reference needs an additional 2 bytes, plus either one or 5 bytes for a repeat. We also need to keep the value of the highest back reference. */ if (c <= -ESC_REF) { int refnum = -c - ESC_REF; compile_block.backref_map |= (refnum < 32)? (1 << refnum) : 1; if (refnum > compile_block.top_backref) compile_block.top_backref = refnum; length += 2; /* For single back reference */ if (ptr[1] == '{' && is_counted_repeat(ptr+2)) { ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; if ((min == 0 && (max == 1 || max == -1)) || (min == 1 && max == -1)) length++; else length += 5; if (ptr[1] == '?') ptr++; } } continue; case '^': /* Single-byte metacharacters */ case '.': case '$': length++; #ifdef SUPPORT_UTF8 lastcharlength = 1; #endif continue; case '*': /* These repeats won't be after brackets; */ case '+': /* those are handled separately */ case '?': length++; goto POSESSIVE; /* A few lines below */ /* This covers the cases of braced repeats after a single char, metachar, class, or back reference. */ case '{': if (!is_counted_repeat(ptr+1)) goto NORMAL_CHAR; ptr = read_repeat_counts(ptr+1, &min, &max, errorptr); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; /* These special cases just insert one extra opcode */ if ((min == 0 && (max == 1 || max == -1)) || (min == 1 && max == -1)) length++; /* These cases might insert additional copies of a preceding character. */ else { #ifdef SUPPORT_UTF8 /* In UTF-8 mode, we should find the length in lastcharlength */ if (utf8) { if (min != 1) { length -= lastcharlength; /* Uncount the original char or metachar */ if (min > 0) length += 3 + lastcharlength; } length += lastcharlength + ((max > 0)? 3 : 1); } else #endif /* Not UTF-8 mode: all characters are one byte */ { if (min != 1) { length--; /* Uncount the original char or metachar */ if (min > 0) length += 4; } length += (max > 0)? 4 : 2; } } if (ptr[1] == '?') ptr++; /* Needs no extra length */ POSESSIVE: /* Test for possessive quantifier */ if (ptr[1] == '+') { ptr++; length += 2 + 2*LINK_SIZE; /* Allow for atomic brackets */ } continue; /* An alternation contains an offset to the next branch or ket. If any ims options changed in the previous branch(es), and/or if we are in a lookbehind assertion, extra space will be needed at the start of the branch. This is handled by branch_extra. */ case '|': length += 1 + LINK_SIZE + branch_extra; continue; /* A character class uses 33 characters provided that all the character values are less than 256. Otherwise, it uses a bit map for low valued characters, and individual items for others. Don't worry about character types that aren't allowed in classes - they'll get picked up during the compile. A character class that contains only one single-byte character uses 2 or 3 bytes, depending on whether it is negated or not. Notice this where we can. (In UTF-8 mode we can do this only for chars < 128.) */ case '[': class_optcount = 0; #ifdef SUPPORT_UTF8 class_utf8 = FALSE; #endif if (*(++ptr) == '^') ptr++; /* Written as a "do" so that an initial ']' is taken as data */ if (*ptr != 0) do { /* Inside \Q...\E everything is literal except \E */ if (inescq) { if (*ptr != '\\' || ptr[1] != 'E') goto NON_SPECIAL_CHARACTER; inescq = FALSE; ptr += 1; continue; } /* Outside \Q...\E, check for escapes */ if (*ptr == '\\') { #ifdef SUPPORT_UTF8 int prevchar = ptr[-1]; #endif int ch = check_escape(&ptr, errorptr, bracount, options, TRUE); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; /* \b is backspace inside a class */ if (-ch == ESC_b) ch = '\b'; /* \Q enters quoting mode */ if (-ch == ESC_Q) { inescq = TRUE; continue; } /* Handle escapes that turn into characters */ if (ch >= 0) { #ifdef SUPPORT_UTF8 if (utf8) { if (ch > 127) class_optcount = 10; /* Ensure > 1 */ if (ch > 255) { uschar buffer[6]; if (!class_utf8) { class_utf8 = TRUE; length += LINK_SIZE + 1 + 1; } length += 1 + ord2utf8(ch, buffer); /* If this wide character is preceded by '-', add an extra 2 to the length in case the previous character was < 128, because in this case the whole range will be put into the list. */ if (prevchar == '-') length += 2; } } #endif class_optcount++; /* for possible optimization */ } else class_optcount = 10; /* \d, \s etc; make sure > 1 */ } /* Check the syntax for POSIX stuff. The bits we actually handle are checked during the real compile phase. */ else if (*ptr == '[' && check_posix_syntax(ptr, &ptr, &compile_block)) { ptr++; class_optcount = 10; /* Make sure > 1 */ } /* Anything else just increments the possible optimization count. If there are wide characters, we are going to have to use an XCLASS. */ else { NON_SPECIAL_CHARACTER: class_optcount++; #ifdef SUPPORT_UTF8 if (utf8) { int ch; int extra = 0; GETCHARLEN(ch, ptr, extra); if (ch > 127) class_optcount = 10; /* No optimization possible */ if (ch > 255) { if (!class_utf8) { class_utf8 = TRUE; length += LINK_SIZE + 1 + 1; } length += 2 + extra; /* If this wide character is preceded by '-', add an extra 2 to the length in case the previous character was < 128, because in this case the whole range will be put into the list. */ if (ptr[-1] == '-') length += 2; /* Advance to the end of this character */ ptr += extra; } } #endif } } while (*(++ptr) != 0 && (inescq || *ptr != ']')); /* Concludes "do" above */ if (*ptr == 0) /* Missing terminating ']' */ { *errorptr = ERR6; goto PCRE_ERROR_RETURN; } /* We can optimize when there was only one optimizable character. Repeats for positive and negated single one-byte chars are handled by the general code. Here, we handle repeats for the class opcodes. */ if (class_optcount == 1) length += 3; else { length += 33; /* A repeat needs either 1 or 5 bytes. If it is a possessive quantifier, we also need extra for wrapping the whole thing in a sub-pattern. */ if (*ptr != 0 && ptr[1] == '{' && is_counted_repeat(ptr+2)) { ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; if ((min == 0 && (max == 1 || max == -1)) || (min == 1 && max == -1)) length++; else length += 5; if (ptr[1] == '+') { ptr++; length += 2 + 2*LINK_SIZE; } else if (ptr[1] == '?') ptr++; } } continue; /* Brackets may be genuine groups or special things */ case '(': branch_newextra = 0; bracket_length = 1 + LINK_SIZE; /* Handle special forms of bracket, which all start (? */ if (ptr[1] == '?') { int set, unset; int *optset; switch (c = ptr[2]) { /* Skip over comments entirely */ case '#': ptr += 3; while (*ptr != 0 && *ptr != ')') ptr++; if (*ptr == 0) { *errorptr = ERR18; goto PCRE_ERROR_RETURN; } continue; /* Non-referencing groups and lookaheads just move the pointer on, and then behave like a non-special bracket, except that they don't increment the count of extracting brackets. Ditto for the "once only" bracket, which is in Perl from version 5.005. */ case ':': case '=': case '!': case '>': ptr += 2; break; /* (?R) specifies a recursive call to the regex, which is an extension to provide the facility which can be obtained by (?p{perl-code}) in Perl 5.6. In Perl 5.8 this has become (??{perl-code}). From PCRE 4.00, items such as (?3) specify subroutine-like "calls" to the appropriate numbered brackets. This includes both recursive and non-recursive calls. (?R) is now synonymous with (?0). */ case 'R': ptr++; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ptr += 2; if (c != 'R') while ((digitab[*(++ptr)] & ctype_digit) != 0); if (*ptr != ')') { *errorptr = ERR29; goto PCRE_ERROR_RETURN; } length += 1 + LINK_SIZE; /* If this item is quantified, it will get wrapped inside brackets so as to use the code for quantified brackets. We jump down and use the code that handles this for real brackets. */ if (ptr[1] == '+' || ptr[1] == '*' || ptr[1] == '?' || ptr[1] == '{') { length += 2 + 2 * LINK_SIZE; /* to make bracketed */ duplength = 5 + 3 * LINK_SIZE; goto HANDLE_QUANTIFIED_BRACKETS; } continue; /* (?C) is an extension which provides "callout" - to provide a bit of the functionality of the Perl (?{...}) feature. An optional number may follow (default is zero). */ case 'C': ptr += 2; while ((digitab[*(++ptr)] & ctype_digit) != 0); if (*ptr != ')') { *errorptr = ERR39; goto PCRE_ERROR_RETURN; } length += 2; continue; /* Named subpatterns are an extension copied from Python */ case 'P': ptr += 3; if (*ptr == '<') { const uschar *p; /* Don't amalgamate; some compilers */ p = ++ptr; /* grumble at autoincrement in declaration */ while ((compile_block.ctypes[*ptr] & ctype_word) != 0) ptr++; if (*ptr != '>') { *errorptr = ERR42; goto PCRE_ERROR_RETURN; } name_count++; if (ptr - p > max_name_size) max_name_size = (ptr - p); break; } if (*ptr == '=' || *ptr == '>') { while ((compile_block.ctypes[*(++ptr)] & ctype_word) != 0); if (*ptr != ')') { *errorptr = ERR42; goto PCRE_ERROR_RETURN; } break; } /* Unknown character after (?P */ *errorptr = ERR41; goto PCRE_ERROR_RETURN; /* Lookbehinds are in Perl from version 5.005 */ case '<': ptr += 3; if (*ptr == '=' || *ptr == '!') { branch_newextra = 1 + LINK_SIZE; length += 1 + LINK_SIZE; /* For the first branch */ break; } *errorptr = ERR24; goto PCRE_ERROR_RETURN; /* Conditionals are in Perl from version 5.005. The bracket must either be followed by a number (for bracket reference) or by an assertion group, or (a PCRE extension) by 'R' for a recursion test. */ case '(': if (ptr[3] == 'R' && ptr[4] == ')') { ptr += 4; length += 3; } else if ((digitab[ptr[3]] & ctype_digit) != 0) { ptr += 4; length += 3; while ((digitab[*ptr] & ctype_digit) != 0) ptr++; if (*ptr != ')') { *errorptr = ERR26; goto PCRE_ERROR_RETURN; } } else /* An assertion must follow */ { ptr++; /* Can treat like ':' as far as spacing is concerned */ if (ptr[2] != '?' || (ptr[3] != '=' && ptr[3] != '!' && ptr[3] != '<') ) { ptr += 2; /* To get right offset in message */ *errorptr = ERR28; goto PCRE_ERROR_RETURN; } } break; /* Else loop checking valid options until ) is met. Anything else is an error. If we are without any brackets, i.e. at top level, the settings act as if specified in the options, so massage the options immediately. This is for backward compatibility with Perl 5.004. */ default: set = unset = 0; optset = &set; ptr += 2; for (;; ptr++) { c = *ptr; switch (c) { case 'i': *optset |= PCRE_CASELESS; continue; case 'm': *optset |= PCRE_MULTILINE; continue; case 's': *optset |= PCRE_DOTALL; continue; case 'x': *optset |= PCRE_EXTENDED; continue; case 'X': *optset |= PCRE_EXTRA; continue; case 'U': *optset |= PCRE_UNGREEDY; continue; case '-': optset = &unset; continue; /* A termination by ')' indicates an options-setting-only item; if this is at the very start of the pattern (indicated by item_count being zero), we use it to set the global options. This is helpful when analyzing the pattern for first characters, etc. Otherwise nothing is done here and it is handled during the compiling process. [Historical note: Up to Perl 5.8, options settings at top level were always global settings, wherever they appeared in the pattern. That is, they were equivalent to an external setting. From 5.8 onwards, they apply only to what follows (which is what you might expect).] */ case ')': if (item_count == 0) { options = (options | set) & (~unset); set = unset = 0; /* To save length */ item_count--; /* To allow for several */ } /* Fall through */ /* A termination by ':' indicates the start of a nested group with the given options set. This is again handled at compile time, but we must allow for compiled space if any of the ims options are set. We also have to allow for resetting space at the end of the group, which is why 4 is added to the length and not just 2. If there are several changes of options within the same group, this will lead to an over-estimate on the length, but this shouldn't matter very much. We also have to allow for resetting options at the start of any alternations, which we do by setting branch_newextra to 2. Finally, we record whether the case-dependent flag ever changes within the regex. This is used by the "required character" code. */ case ':': if (((set|unset) & PCRE_IMS) != 0) { length += 4; branch_newextra = 2; if (((set|unset) & PCRE_CASELESS) != 0) options |= PCRE_ICHANGED; } goto END_OPTIONS; /* Unrecognized option character */ default: *errorptr = ERR12; goto PCRE_ERROR_RETURN; } } /* If we hit a closing bracket, that's it - this is a freestanding option-setting. We need to ensure that branch_extra is updated if necessary. The only values branch_newextra can have here are 0 or 2. If the value is 2, then branch_extra must either be 2 or 5, depending on whether this is a lookbehind group or not. */ END_OPTIONS: if (c == ')') { if (branch_newextra == 2 && (branch_extra == 0 || branch_extra == 1+LINK_SIZE)) branch_extra += branch_newextra; continue; } /* If options were terminated by ':' control comes here. Fall through to handle the group below. */ } } /* Extracting brackets must be counted so we can process escapes in a Perlish way. If the number exceeds EXTRACT_BASIC_MAX we are going to need an additional 3 bytes of store per extracting bracket. However, if PCRE_NO_AUTO)CAPTURE is set, unadorned brackets become non-capturing, so we must leave the count alone (it will aways be zero). */ else if ((options & PCRE_NO_AUTO_CAPTURE) == 0) { bracount++; if (bracount > EXTRACT_BASIC_MAX) bracket_length += 3; } /* Save length for computing whole length at end if there's a repeat that requires duplication of the group. Also save the current value of branch_extra, and start the new group with the new value. If non-zero, this will either be 2 for a (?imsx: group, or 3 for a lookbehind assertion. */ if (brastackptr >= sizeof(brastack)/sizeof(int)) { *errorptr = ERR19; goto PCRE_ERROR_RETURN; } bralenstack[brastackptr] = branch_extra; branch_extra = branch_newextra; brastack[brastackptr++] = length; length += bracket_length; continue; /* Handle ket. Look for subsequent max/min; for certain sets of values we have to replicate this bracket up to that many times. If brastackptr is 0 this is an unmatched bracket which will generate an error, but take care not to try to access brastack[-1] when computing the length and restoring the branch_extra value. */ case ')': length += 1 + LINK_SIZE; if (brastackptr > 0) { duplength = length - brastack[--brastackptr]; branch_extra = bralenstack[brastackptr]; } else duplength = 0; /* The following code is also used when a recursion such as (?3) is followed by a quantifier, because in that case, it has to be wrapped inside brackets so that the quantifier works. The value of duplength must be set before arrival. */ HANDLE_QUANTIFIED_BRACKETS: /* Leave ptr at the final char; for read_repeat_counts this happens automatically; for the others we need an increment. */ if ((c = ptr[1]) == '{' && is_counted_repeat(ptr+2)) { ptr = read_repeat_counts(ptr+2, &min, &max, errorptr); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; } else if (c == '*') { min = 0; max = -1; ptr++; } else if (c == '+') { min = 1; max = -1; ptr++; } else if (c == '?') { min = 0; max = 1; ptr++; } else { min = 1; max = 1; } /* If the minimum is zero, we have to allow for an OP_BRAZERO before the group, and if the maximum is greater than zero, we have to replicate maxval-1 times; each replication acquires an OP_BRAZERO plus a nesting bracket set. */ if (min == 0) { length++; if (max > 0) length += (max - 1) * (duplength + 3 + 2*LINK_SIZE); } /* When the minimum is greater than zero, we have to replicate up to minval-1 times, with no additions required in the copies. Then, if there is a limited maximum we have to replicate up to maxval-1 times allowing for a BRAZERO item before each optional copy and nesting brackets for all but one of the optional copies. */ else { length += (min - 1) * duplength; if (max > min) /* Need this test as max=-1 means no limit */ length += (max - min) * (duplength + 3 + 2*LINK_SIZE) - (2 + 2*LINK_SIZE); } /* Allow space for once brackets for "possessive quantifier" */ if (ptr[1] == '+') { ptr++; length += 2 + 2*LINK_SIZE; } continue; /* Non-special character. For a run of such characters the length required is the number of characters + 2, except that the maximum run length is MAXLIT. We won't get a skipped space or a non-data escape or the start of a # comment as the first character, so the length can't be zero. */ NORMAL_CHAR: default: length += 2; runlength = 0; do { #ifdef SUPPORT_UTF8 lastcharlength = 1; /* Need length of last char for UTF-8 repeats */ #endif /* If in a \Q...\E sequence, check for end; otherwise it's a literal */ if (inescq) { if (c == '\\' && ptr[1] == 'E') { inescq = FALSE; ptr++; } else runlength++; continue; } /* Skip whitespace and comments for /x */ if ((options & PCRE_EXTENDED) != 0) { if ((compile_block.ctypes[c] & ctype_space) != 0) continue; if (c == '#') { /* The space before the ; is to avoid a warning on a silly compiler on the Macintosh. */ while ((c = *(++ptr)) != 0 && c != NEWLINE) ; continue; } } /* Backslash may introduce a data char or a metacharacter; stop the string before the latter. */ if (c == '\\') { const uschar *saveptr = ptr; c = check_escape(&ptr, errorptr, bracount, options, FALSE); if (*errorptr != NULL) goto PCRE_ERROR_RETURN; if (c < 0) { ptr = saveptr; break; } /* In UTF-8 mode, add on the number of additional bytes needed to encode this character, and save the total length in case this is a final char that is repeated. */ #ifdef SUPPORT_UTF8 if (utf8 && c > 127) { int i; for (i = 0; i < sizeof(utf8_table1)/sizeof(int); i++) if (c <= utf8_table1[i]) break; runlength += i; lastcharlength += i; } #endif } /* Ordinary character or single-char escape */ runlength++; } /* This "while" is the end of the "do" above. */ while (runlength < MAXLIT && (compile_block.ctypes[c = *(++ptr)] & ctype_meta) == 0); /* If we hit a meta-character, back off to point to it */ if (runlength < MAXLIT) ptr--; /* If the last char in the string is a UTF-8 multibyte character, we must set lastcharlength correctly. If it was specified as an escape, this will already have been done above. However, we also have to support in-line UTF-8 characters, so check backwards from where we are. */ #ifdef SUPPORT_UTF8 if (utf8) { const uschar *lastptr = ptr - 1; if ((*lastptr & 0x80) != 0) { while((*lastptr & 0xc0) == 0x80) lastptr--; lastcharlength = ptr - lastptr; } } #endif length += runlength; continue; } } length += 2 + LINK_SIZE; /* For final KET and END */ if (length > MAX_PATTERN_SIZE) { *errorptr = ERR20; return NULL; } /* Compute the size of data block needed and get it, either from malloc or externally provided function. */ size = length + sizeof(real_pcre) + name_count * (max_name_size + 3); re = (real_pcre *)(pcre_malloc)(size); if (re == NULL) { *errorptr = ERR21; return NULL; } /* Put in the magic number, and save the size, options, and table pointer */ re->magic_number = MAGIC_NUMBER; re->size = size; re->options = options; re->tables = tables; re->name_entry_size = max_name_size + 3; re->name_count = name_count; /* The starting points of the name/number translation table and of the code are passed around in the compile data block. */ compile_block.names_found = 0; compile_block.name_entry_size = max_name_size + 3; compile_block.name_table = (uschar *)re + sizeof(real_pcre); codestart = compile_block.name_table + re->name_entry_size * re->name_count; compile_block.start_code = codestart; compile_block.req_varyopt = 0; /* Set up a starting, non-extracting bracket, then compile the expression. On error, *errorptr will be set non-NULL, so we don't need to look at the result of the function here. */ ptr = (const uschar *)pattern; code = (uschar *)codestart; *code = OP_BRA; bracount = 0; (void)compile_regex(options, options & PCRE_IMS, &bracount, &code, &ptr, errorptr, FALSE, 0, &firstbyte, &reqbyte, NULL, &compile_block); re->top_bracket = bracount; re->top_backref = compile_block.top_backref; /* If not reached end of pattern on success, there's an excess bracket. */ if (*errorptr == NULL && *ptr != 0) *errorptr = ERR22; /* Fill in the terminating state and check for disastrous overflow, but if debugging, leave the test till after things are printed out. */ *code++ = OP_END; #ifndef DEBUG if (code - codestart > length) *errorptr = ERR23; #endif /* Give an error if there's back reference to a non-existent capturing subpattern. */ if (re->top_backref > re->top_bracket) *errorptr = ERR15; /* Failed to compile, or error while post-processing */ if (*errorptr != NULL) { (pcre_free)(re); PCRE_ERROR_RETURN: *erroroffset = ptr - (const uschar *)pattern; return NULL; } /* If the anchored option was not passed, set the flag if we can determine that the pattern is anchored by virtue of ^ characters or \A or anything else (such as starting with .* when DOTALL is set). Otherwise, if we know what the first character has to be, save it, because that speeds up unanchored matches no end. If not, see if we can set the PCRE_STARTLINE flag. This is helpful for multiline matches when all branches start with ^. and also when all branches start with .* for non-DOTALL matches. */ if ((options & PCRE_ANCHORED) == 0) { int temp_options = options; if (is_anchored(codestart, &temp_options, 0, compile_block.backref_map)) re->options |= PCRE_ANCHORED; else { if (firstbyte < 0) firstbyte = find_firstassertedchar(codestart, &temp_options, FALSE); if (firstbyte >= 0) /* Remove caseless flag for non-caseable chars */ { int ch = firstbyte & 255; re->first_byte = ((firstbyte & REQ_CASELESS) != 0 && compile_block.fcc[ch] == ch)? ch : firstbyte; re->options |= PCRE_FIRSTSET; } else if (is_startline(codestart, 0, compile_block.backref_map)) re->options |= PCRE_STARTLINE; } } /* For an anchored pattern, we use the "required byte" only if it follows a variable length item in the regex. Remove the caseless flag for non-caseable chars. */ if (reqbyte >= 0 && ((re->options & PCRE_ANCHORED) == 0 || (reqbyte & REQ_VARY) != 0)) { int ch = reqbyte & 255; re->req_byte = ((reqbyte & REQ_CASELESS) != 0 && compile_block.fcc[ch] == ch)? (reqbyte & ~REQ_CASELESS) : reqbyte; re->options |= PCRE_REQCHSET; } /* Print out the compiled data for debugging */ #ifdef DEBUG printf("Length = %d top_bracket = %d top_backref = %d\n", length, re->top_bracket, re->top_backref); if (re->options != 0) { printf("%s%s%s%s%s%s%s%s%s\n", ((re->options & PCRE_ANCHORED) != 0)? "anchored " : "", ((re->options & PCRE_CASELESS) != 0)? "caseless " : "", ((re->options & PCRE_ICHANGED) != 0)? "case state changed " : "", ((re->options & PCRE_EXTENDED) != 0)? "extended " : "", ((re->options & PCRE_MULTILINE) != 0)? "multiline " : "", ((re->options & PCRE_DOTALL) != 0)? "dotall " : "", ((re->options & PCRE_DOLLAR_ENDONLY) != 0)? "endonly " : "", ((re->options & PCRE_EXTRA) != 0)? "extra " : "", ((re->options & PCRE_UNGREEDY) != 0)? "ungreedy " : ""); } if ((re->options & PCRE_FIRSTSET) != 0) { int ch = re->first_byte & 255; const char *caseless = ((re->first_byte & REQ_CASELESS) == 0)? "" : " (caseless)"; if (isprint(ch)) printf("First char = %c%s\n", ch, caseless); else printf("First char = \\x%02x%s\n", ch, caseless); } if ((re->options & PCRE_REQCHSET) != 0) { int ch = re->req_byte & 255; const char *caseless = ((re->req_byte & REQ_CASELESS) == 0)? "" : " (caseless)"; if (isprint(ch)) printf("Req char = %c%s\n", ch, caseless); else printf("Req char = \\x%02x%s\n", ch, caseless); } print_internals(re, stdout); /* This check is done here in the debugging case so that the code that was compiled can be seen. */ if (code - codestart > length) { *errorptr = ERR23; (pcre_free)(re); *erroroffset = ptr - (uschar *)pattern; return NULL; } #endif return (pcre *)re; } /************************************************* * Match a back-reference * *************************************************/ /* If a back reference hasn't been set, the length that is passed is greater than the number of characters left in the string, so the match fails. Arguments: offset index into the offset vector eptr points into the subject length length to be matched md points to match data block ims the ims flags Returns: TRUE if matched */ static BOOL match_ref(int offset, register const uschar *eptr, int length, match_data *md, unsigned long int ims) { const uschar *p = md->start_subject + md->offset_vector[offset]; #ifdef DEBUG if (eptr >= md->end_subject) printf("matching subject "); else { printf("matching subject "); pchars(eptr, length, TRUE, md); } printf(" against backref "); pchars(p, length, FALSE, md); printf("\n"); #endif /* Always fail if not enough characters left */ if (length > md->end_subject - eptr) return FALSE; /* Separate the caselesss case for speed */ if ((ims & PCRE_CASELESS) != 0) { while (length-- > 0) if (md->lcc[*p++] != md->lcc[*eptr++]) return FALSE; } else { while (length-- > 0) if (*p++ != *eptr++) return FALSE; } return TRUE; } #ifdef SUPPORT_UTF8 /************************************************* * Match character against an XCLASS * *************************************************/ /* This function is called from within the XCLASS code below, to match a character against an extended class which might match values > 255. Arguments: c the character data points to the flag byte of the XCLASS data Returns: TRUE if character matches, else FALSE */ static BOOL match_xclass(int c, const uschar *data) { int t; BOOL negated = (*data & XCL_NOT) != 0; /* Character values < 256 are matched against a bitmap, if one is present. If not, we still carry on, because there may be ranges that start below 256 in the additional data. */ if (c < 256) { if ((*data & XCL_MAP) != 0 && (data[1 + c/8] & (1 << (c&7))) != 0) return !negated; /* char found */ } /* Now match against the list of large chars or ranges that end with a large char. First skip the bit map if present. */ if ((*data++ & XCL_MAP) != 0) data += 32; while ((t = *data++) != XCL_END) { int x, y; GETCHARINC(x, data); if (t == XCL_SINGLE) { if (c == x) return !negated; } else { GETCHARINC(y, data); if (c >= x && c <= y) return !negated; } } return negated; /* char was not found */ } #endif /*************************************************************************** **************************************************************************** RECURSION IN THE match() FUNCTION The match() function is highly recursive. Some regular expressions can cause it to recurse thousands of times. I was writing for Unix, so I just let it call itself recursively. This uses the stack for saving everything that has to be saved for a recursive call. On Unix, the stack can be large, and this works fine. It turns out that on non-Unix systems there are problems with programs that use a lot of stack. (This despite the fact that every last chip has oodles of memory these days, and techniques for extending the stack have been known for decades.) So.... There is a fudge, triggered by defining NO_RECURSE, which avoids recursive calls by keeping local variables that need to be preserved in blocks of memory obtained from malloc instead instead of on the stack. Macros are used to achieve this so that the actual code doesn't look very different to what it always used to. **************************************************************************** ***************************************************************************/ /* These versions of the macros use the stack, as normal */ #ifndef NO_RECURSE #define REGISTER register #define RMATCH(rx,ra,rb,rc,rd,re,rf,rg) rx = match(ra,rb,rc,rd,re,rf,rg) #define RRETURN(ra) return ra #else /* These versions of the macros manage a private stack on the heap. Note that the rd argument of RMATCH isn't actually used. It's the md argument of match(), which never actually changes. */ #define REGISTER #define RMATCH(rx,ra,rb,rc,rd,re,rf,rg)\ {\ heapframe *newframe = (pcre_stack_malloc)(sizeof(heapframe));\ if (setjmp(frame->Xwhere) == 0)\ {\ newframe->Xeptr = ra;\ newframe->Xecode = rb;\ newframe->Xoffset_top = rc;\ newframe->Xims = re;\ newframe->Xeptrb = rf;\ newframe->Xflags = rg;\ newframe->Xprevframe = frame;\ frame = newframe;\ DPRINTF(("restarting from line %d\n", __LINE__));\ goto HEAP_RECURSE;\ }\ else\ {\ DPRINTF(("longjumped back to line %d\n", __LINE__));\ frame = md->thisframe;\ rx = frame->Xresult;\ }\ } #define RRETURN(ra)\ {\ heapframe *newframe = frame;\ frame = newframe->Xprevframe;\ (pcre_stack_free)(newframe);\ if (frame != NULL)\ {\ frame->Xresult = ra;\ md->thisframe = frame;\ longjmp(frame->Xwhere, 1);\ }\ return ra;\ } /* Structure for remembering the local variables in a private frame */ typedef struct heapframe { struct heapframe *Xprevframe; /* Function arguments that may change */ const uschar *Xeptr; const uschar *Xecode; int Xoffset_top; long int Xims; eptrblock *Xeptrb; int Xflags; /* Function local variables */ const uschar *Xcallpat; const uschar *Xcharptr; const uschar *Xdata; const uschar *Xlastptr; const uschar *Xnext; const uschar *Xpp; const uschar *Xprev; const uschar *Xsaved_eptr; recursion_info Xnew_recursive; BOOL Xcur_is_word; BOOL Xcondition; BOOL Xminimize; BOOL Xprev_is_word; unsigned long int Xoriginal_ims; int Xctype; int Xfc; int Xfi; int Xlength; int Xmax; int Xmin; int Xnumber; int Xoffset; int Xop; int Xsave_capture_last; int Xsave_offset1, Xsave_offset2, Xsave_offset3; int Xstacksave[REC_STACK_SAVE_MAX]; eptrblock Xnewptrb; /* Place to pass back result, and where to jump back to */ int Xresult; jmp_buf Xwhere; } heapframe; #endif /*************************************************************************** ***************************************************************************/ /************************************************* * Match from current position * *************************************************/ /* On entry ecode points to the first opcode, and eptr to the first character in the subject string, while eptrb holds the value of eptr at the start of the last bracketed group - used for breaking infinite loops matching zero-length strings. This function is called recursively in many circumstances. Whenever it returns a negative (error) response, the outer incarnation must also return the same response. Performance note: It might be tempting to extract commonly used fields from the md structure (e.g. utf8, end_subject) into individual variables to improve performance. Tests using gcc on a SPARC disproved this; in the first case, it made performance worse. Arguments: eptr pointer in subject ecode position in code offset_top current top pointer md pointer to "static" info for the match ims current /i, /m, and /s options eptrb pointer to chain of blocks containing eptr at start of brackets - for testing for empty matches flags can contain match_condassert - this is an assertion condition match_isgroup - this is the start of a bracketed group Returns: MATCH_MATCH if matched ) these values are >= 0 MATCH_NOMATCH if failed to match ) a negative PCRE_ERROR_xxx value if aborted by an error condition (e.g. stopped by recursion limit) */ static int match(REGISTER const uschar *eptr, REGISTER const uschar *ecode, int offset_top, match_data *md, unsigned long int ims, eptrblock *eptrb, int flags) { /* These variables do not need to be preserved over recursion in this function, so they can be ordinary variables in all cases. Mark them with "register" because they are used a lot in loops. */ register int rrc; /* Returns from recursive calls */ register int i; /* Used for loops not involving calls to RMATCH() */ register int c; /* Character values not kept over RMATCH() calls */ /* When recursion is not being used, all "local" variables that have to be preserved over calls to RMATCH() are part of a "frame" which is obtained from heap storage. Set up the top-level frame here; others are obtained from the heap whenever RMATCH() does a "recursion". See the macro definitions above. */ #ifdef NO_RECURSE heapframe *frame = (pcre_stack_malloc)(sizeof(heapframe)); frame->Xprevframe = NULL; /* Marks the top level */ /* Copy in the original argument variables */ frame->Xeptr = eptr; frame->Xecode = ecode; frame->Xoffset_top = offset_top; frame->Xims = ims; frame->Xeptrb = eptrb; frame->Xflags = flags; /* This is where control jumps back to to effect "recursion" */ HEAP_RECURSE: /* Macros make the argument variables come from the current frame */ #define eptr frame->Xeptr #define ecode frame->Xecode #define offset_top frame->Xoffset_top #define ims frame->Xims #define eptrb frame->Xeptrb #define flags frame->Xflags /* Ditto for the local variables */ #define callpat frame->Xcallpat #define charptr frame->Xcharptr #define data frame->Xdata #define lastptr frame->Xlastptr #define next frame->Xnext #define pp frame->Xpp #define prev frame->Xprev #define saved_eptr frame->Xsaved_eptr #define new_recursive frame->Xnew_recursive #define cur_is_word frame->Xcur_is_word #define condition frame->Xcondition #define minimize frame->Xminimize #define prev_is_word frame->Xprev_is_word #define original_ims frame->Xoriginal_ims #define ctype frame->Xctype #define fc frame->Xfc #define fi frame->Xfi #define length frame->Xlength #define max frame->Xmax #define min frame->Xmin #define number frame->Xnumber #define offset frame->Xoffset #define op frame->Xop #define save_capture_last frame->Xsave_capture_last #define save_offset1 frame->Xsave_offset1 #define save_offset2 frame->Xsave_offset2 #define save_offset3 frame->Xsave_offset3 #define stacksave frame->Xstacksave #define newptrb frame->Xnewptrb /* When recursion is being used, local variables are allocated on the stack and get preserved during recursion in the normal way. In this environment, fi and i, and fc and c, can be the same variables. */ #else #define fi i #define fc c const uschar *callpat; /* Many of these variables are used ony */ #if 0 const uschar *charptr; /* small blocks of the code. My normal */ const uschar *lastptr; /* them within each of those blocks. */ #endif const uschar *data; /* style of coding would have declared */ const uschar *next; /* However, in order to accommodate the */ const uschar *pp; /* version of this code that uses an */ const uschar *prev; /* external "stack" implemented on the */ const uschar *saved_eptr; /* heap, it is easier to declare them */ /* all here, so the declarations can */ recursion_info new_recursive; /* be cut out in a block. The only */ /* declarations within blocks below are */ BOOL cur_is_word; /* for variables that do not have to */ BOOL condition; /* be preserved over a recursive call */ BOOL minimize; /* to RMATCH(). */ BOOL prev_is_word; unsigned long int original_ims; int ctype; int length; int max; int min; int number; int offset; int op; int save_capture_last; int save_offset1, save_offset2, save_offset3; int stacksave[REC_STACK_SAVE_MAX]; eptrblock newptrb; #endif /* OK, now we can get on with the real code of the function. Recursion is specified by the macros RMATCH and RRETURN. When NO_RECURSE is *not* defined, these just turn into a recursive call to match() and a "return", respectively. However, RMATCH isn't like a function call because it's quite a complicated macro. It has to be used in one particular way. This shouldn't, however, impact performance when true recursion is being used. */ if (md->match_call_count++ >= md->match_limit) RRETURN(PCRE_ERROR_MATCHLIMIT); original_ims = ims; /* Save for resetting on ')' */ /* At the start of a bracketed group, add the current subject pointer to the stack of such pointers, to be re-instated at the end of the group when we hit the closing ket. When match() is called in other circumstances, we don't add to this stack. */ if ((flags & match_isgroup) != 0) { newptrb.epb_prev = eptrb; newptrb.epb_saved_eptr = eptr; eptrb = &newptrb; } /* Now start processing the operations. */ for (;;) { op = *ecode; minimize = FALSE; /* Opening capturing bracket. If there is space in the offset vector, save the current subject position in the working slot at the top of the vector. We mustn't change the current values of the data slot, because they may be set from a previous iteration of this group, and be referred to by a reference inside the group. If the bracket fails to match, we need to restore this value and also the values of the final offsets, in case they were set by a previous iteration of the same bracket. If there isn't enough space in the offset vector, treat this as if it were a non-capturing bracket. Don't worry about setting the flag for the error case here; that is handled in the code for KET. */ if (op > OP_BRA) { number = op - OP_BRA; /* For extended extraction brackets (large number), we have to fish out the number from a dummy opcode at the start. */ if (number > EXTRACT_BASIC_MAX) number = GET2(ecode, 2+LINK_SIZE); offset = number << 1; #ifdef DEBUG printf("start bracket %d subject=", number); pchars(eptr, 16, TRUE, md); printf("\n"); #endif if (offset < md->offset_max) { save_offset1 = md->offset_vector[offset]; save_offset2 = md->offset_vector[offset+1]; save_offset3 = md->offset_vector[md->offset_end - number]; save_capture_last = md->capture_last; DPRINTF(("saving %d %d %d\n", save_offset1, save_offset2, save_offset3)); md->offset_vector[md->offset_end - number] = eptr - md->start_subject; do { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); md->capture_last = save_capture_last; ecode += GET(ecode, 1); } while (*ecode == OP_ALT); DPRINTF(("bracket %d failed\n", number)); md->offset_vector[offset] = save_offset1; md->offset_vector[offset+1] = save_offset2; md->offset_vector[md->offset_end - number] = save_offset3; RRETURN(MATCH_NOMATCH); } /* Insufficient room for saving captured contents */ else op = OP_BRA; } /* Other types of node can be handled by a switch */ switch(op) { case OP_BRA: /* Non-capturing bracket: optimized */ DPRINTF(("start bracket 0\n")); do { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); ecode += GET(ecode, 1); } while (*ecode == OP_ALT); DPRINTF(("bracket 0 failed\n")); RRETURN(MATCH_NOMATCH); /* Conditional group: compilation checked that there are no more than two branches. If the condition is false, skipping the first branch takes us past the end if there is only one branch, but that's OK because that is exactly what going to the ket would do. */ case OP_COND: if (ecode[LINK_SIZE+1] == OP_CREF) /* Condition extract or recurse test */ { offset = GET2(ecode, LINK_SIZE+2) << 1; /* Doubled ref number */ condition = (offset == CREF_RECURSE * 2)? (md->recursive != NULL) : (offset < offset_top && md->offset_vector[offset] >= 0); RMATCH(rrc, eptr, ecode + (condition? (LINK_SIZE + 4) : (LINK_SIZE + 1 + GET(ecode, 1))), offset_top, md, ims, eptrb, match_isgroup); RRETURN(rrc); } /* The condition is an assertion. Call match() to evaluate it - setting the final argument TRUE causes it to stop at the end of an assertion. */ else { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, match_condassert | match_isgroup); if (rrc == MATCH_MATCH) { ecode += 1 + LINK_SIZE + GET(ecode, LINK_SIZE+2); while (*ecode == OP_ALT) ecode += GET(ecode, 1); } else if (rrc != MATCH_NOMATCH) { RRETURN(rrc); /* Need braces because of following else */ } else ecode += GET(ecode, 1); RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, match_isgroup); RRETURN(rrc); } /* Control never reaches here */ /* Skip over conditional reference or large extraction number data if encountered. */ case OP_CREF: case OP_BRANUMBER: ecode += 3; break; /* End of the pattern. If we are in a recursion, we should restore the offsets appropriately and continue from after the call. */ case OP_END: if (md->recursive != NULL && md->recursive->group_num == 0) { recursion_info *rec = md->recursive; DPRINTF(("Hit the end in a (?0) recursion\n")); md->recursive = rec->prevrec; memmove(md->offset_vector, rec->offset_save, rec->saved_max * sizeof(int)); md->start_match = rec->save_start; ims = original_ims; ecode = rec->after_call; break; } /* Otherwise, if PCRE_NOTEMPTY is set, fail if we have matched an empty string - backtracking will then try other alternatives, if any. */ if (md->notempty && eptr == md->start_match) RRETURN(MATCH_NOMATCH); md->end_match_ptr = eptr; /* Record where we ended */ md->end_offset_top = offset_top; /* and how many extracts were taken */ RRETURN(MATCH_MATCH); /* Change option settings */ case OP_OPT: ims = ecode[1]; ecode += 2; DPRINTF(("ims set to %02lx\n", ims)); break; /* Assertion brackets. Check the alternative branches in turn - the matching won't pass the KET for an assertion. If any one branch matches, the assertion is true. Lookbehind assertions have an OP_REVERSE item at the start of each branch to move the current point backwards, so the code at this level is identical to the lookahead case. */ case OP_ASSERT: case OP_ASSERTBACK: do { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, match_isgroup); if (rrc == MATCH_MATCH) break; if (rrc != MATCH_NOMATCH) RRETURN(rrc); ecode += GET(ecode, 1); } while (*ecode == OP_ALT); if (*ecode == OP_KET) RRETURN(MATCH_NOMATCH); /* If checking an assertion for a condition, return MATCH_MATCH. */ if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH); /* Continue from after the assertion, updating the offsets high water mark, since extracts may have been taken during the assertion. */ do ecode += GET(ecode,1); while (*ecode == OP_ALT); ecode += 1 + LINK_SIZE; offset_top = md->end_offset_top; continue; /* Negative assertion: all branches must fail to match */ case OP_ASSERT_NOT: case OP_ASSERTBACK_NOT: do { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, NULL, match_isgroup); if (rrc == MATCH_MATCH) RRETURN(MATCH_NOMATCH); if (rrc != MATCH_NOMATCH) RRETURN(rrc); ecode += GET(ecode,1); } while (*ecode == OP_ALT); if ((flags & match_condassert) != 0) RRETURN(MATCH_MATCH); ecode += 1 + LINK_SIZE; continue; /* Move the subject pointer back. This occurs only at the start of each branch of a lookbehind assertion. If we are too close to the start to move back, this match function fails. When working with UTF-8 we move back a number of characters, not bytes. */ case OP_REVERSE: #ifdef SUPPORT_UTF8 if (md->utf8) { c = GET(ecode,1); for (i = 0; i < c; i++) { eptr--; if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); BACKCHAR(eptr) } } else #endif /* No UTF-8 support, or not in UTF-8 mode: count is byte count */ { eptr -= GET(ecode,1); if (eptr < md->start_subject) RRETURN(MATCH_NOMATCH); } /* Skip to next op code */ ecode += 1 + LINK_SIZE; break; /* The callout item calls an external function, if one is provided, passing details of the match so far. This is mainly for debugging, though the function is able to force a failure. */ case OP_CALLOUT: if (pcre_callout != NULL) { pcre_callout_block cb; cb.version = 0; /* Version 0 of the callout block */ cb.callout_number = ecode[1]; cb.offset_vector = md->offset_vector; cb.subject = (const char *)md->start_subject; cb.subject_length = md->end_subject - md->start_subject; cb.start_match = md->start_match - md->start_subject; cb.current_position = eptr - md->start_subject; cb.capture_top = offset_top/2; cb.capture_last = md->capture_last; cb.callout_data = md->callout_data; if ((rrc = (*pcre_callout)(&cb)) > 0) RRETURN(MATCH_NOMATCH); if (rrc < 0) RRETURN(rrc); } ecode += 2; break; /* Recursion either matches the current regex, or some subexpression. The offset data is the offset to the starting bracket from the start of the whole pattern. (This is so that it works from duplicated subpatterns.) If there are any capturing brackets started but not finished, we have to save their starting points and reinstate them after the recursion. However, we don't know how many such there are (offset_top records the completed total) so we just have to save all the potential data. There may be up to 65535 such values, which is too large to put on the stack, but using malloc for small numbers seems expensive. As a compromise, the stack is used when there are no more than REC_STACK_SAVE_MAX values to store; otherwise malloc is used. A problem is what to do if the malloc fails ... there is no way of returning to the top level with an error. Save the top REC_STACK_SAVE_MAX values on the stack, and accept that the rest may be wrong. There are also other values that have to be saved. We use a chained sequence of blocks that actually live on the stack. Thanks to Robin Houston for the original version of this logic. */ case OP_RECURSE: { callpat = md->start_code + GET(ecode, 1); new_recursive.group_num = *callpat - OP_BRA; /* For extended extraction brackets (large number), we have to fish out the number from a dummy opcode at the start. */ if (new_recursive.group_num > EXTRACT_BASIC_MAX) new_recursive.group_num = GET2(callpat, 2+LINK_SIZE); /* Add to "recursing stack" */ new_recursive.prevrec = md->recursive; md->recursive = &new_recursive; /* Find where to continue from afterwards */ ecode += 1 + LINK_SIZE; new_recursive.after_call = ecode; /* Now save the offset data. */ new_recursive.saved_max = md->offset_end; if (new_recursive.saved_max <= REC_STACK_SAVE_MAX) new_recursive.offset_save = stacksave; else { new_recursive.offset_save = (int *)(pcre_malloc)(new_recursive.saved_max * sizeof(int)); if (new_recursive.offset_save == NULL) RRETURN(PCRE_ERROR_NOMEMORY); } memcpy(new_recursive.offset_save, md->offset_vector, new_recursive.saved_max * sizeof(int)); new_recursive.save_start = md->start_match; md->start_match = eptr; /* OK, now we can do the recursion. For each top-level alternative we restore the offset and recursion data. */ DPRINTF(("Recursing into group %d\n", new_recursive.group_num)); do { RMATCH(rrc, eptr, callpat + 1 + LINK_SIZE, offset_top, md, ims, eptrb, match_isgroup); if (rrc == MATCH_MATCH) { md->recursive = new_recursive.prevrec; if (new_recursive.offset_save != stacksave) (pcre_free)(new_recursive.offset_save); RRETURN(MATCH_MATCH); } else if (rrc != MATCH_NOMATCH) RRETURN(rrc); md->recursive = &new_recursive; memcpy(md->offset_vector, new_recursive.offset_save, new_recursive.saved_max * sizeof(int)); callpat += GET(callpat, 1); } while (*callpat == OP_ALT); DPRINTF(("Recursion didn't match\n")); md->recursive = new_recursive.prevrec; if (new_recursive.offset_save != stacksave) (pcre_free)(new_recursive.offset_save); RRETURN(MATCH_NOMATCH); } /* Control never reaches here */ /* "Once" brackets are like assertion brackets except that after a match, the point in the subject string is not moved back. Thus there can never be a move back into the brackets. Friedl calls these "atomic" subpatterns. Check the alternative branches in turn - the matching won't pass the KET for this kind of subpattern. If any one branch matches, we carry on as at the end of a normal bracket, leaving the subject pointer. */ case OP_ONCE: { prev = ecode; saved_eptr = eptr; do { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, match_isgroup); if (rrc == MATCH_MATCH) break; if (rrc != MATCH_NOMATCH) RRETURN(rrc); ecode += GET(ecode,1); } while (*ecode == OP_ALT); /* If hit the end of the group (which could be repeated), fail */ if (*ecode != OP_ONCE && *ecode != OP_ALT) RRETURN(MATCH_NOMATCH); /* Continue as from after the assertion, updating the offsets high water mark, since extracts may have been taken. */ do ecode += GET(ecode,1); while (*ecode == OP_ALT); offset_top = md->end_offset_top; eptr = md->end_match_ptr; /* For a non-repeating ket, just continue at this level. This also happens for a repeating ket if no characters were matched in the group. This is the forcible breaking of infinite loops as implemented in Perl 5.005. If there is an options reset, it will get obeyed in the normal course of events. */ if (*ecode == OP_KET || eptr == saved_eptr) { ecode += 1+LINK_SIZE; break; } /* The repeating kets try the rest of the pattern or restart from the preceding bracket, in the appropriate order. We need to reset any options that changed within the bracket before re-running it, so check the next opcode. */ if (ecode[1+LINK_SIZE] == OP_OPT) { ims = (ims & ~PCRE_IMS) | ecode[4]; DPRINTF(("ims set to %02lx at group repeat\n", ims)); } if (*ecode == OP_KETRMIN) { RMATCH(rrc, eptr, ecode + 1 + LINK_SIZE, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); } else /* OP_KETRMAX */ { RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); } } RRETURN(MATCH_NOMATCH); /* An alternation is the end of a branch; scan along to find the end of the bracketed group and go to there. */ case OP_ALT: do ecode += GET(ecode,1); while (*ecode == OP_ALT); break; /* BRAZERO and BRAMINZERO occur just before a bracket group, indicating that it may occur zero times. It may repeat infinitely, or not at all - i.e. it could be ()* or ()? in the pattern. Brackets with fixed upper repeat limits are compiled as a number of copies, with the optional ones preceded by BRAZERO or BRAMINZERO. */ case OP_BRAZERO: { next = ecode+1; RMATCH(rrc, eptr, next, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); do next += GET(next,1); while (*next == OP_ALT); ecode = next + 1+LINK_SIZE; } break; case OP_BRAMINZERO: { next = ecode+1; do next += GET(next,1); while (*next == OP_ALT); RMATCH(rrc, eptr, next + 1+LINK_SIZE, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); ecode++; } break; /* End of a group, repeated or non-repeating. If we are at the end of an assertion "group", stop matching and return MATCH_MATCH, but record the current high water mark for use by positive assertions. Do this also for the "once" (not-backup up) groups. */ case OP_KET: case OP_KETRMIN: case OP_KETRMAX: { prev = ecode - GET(ecode, 1); saved_eptr = eptrb->epb_saved_eptr; /* Back up the stack of bracket start pointers. */ eptrb = eptrb->epb_prev; if (*prev == OP_ASSERT || *prev == OP_ASSERT_NOT || *prev == OP_ASSERTBACK || *prev == OP_ASSERTBACK_NOT || *prev == OP_ONCE) { md->end_match_ptr = eptr; /* For ONCE */ md->end_offset_top = offset_top; RRETURN(MATCH_MATCH); } /* In all other cases except a conditional group we have to check the group number back at the start and if necessary complete handling an extraction by setting the offsets and bumping the high water mark. */ if (*prev != OP_COND) { number = *prev - OP_BRA; /* For extended extraction brackets (large number), we have to fish out the number from a dummy opcode at the start. */ if (number > EXTRACT_BASIC_MAX) number = GET2(prev, 2+LINK_SIZE); offset = number << 1; #ifdef DEBUG printf("end bracket %d", number); printf("\n"); #endif /* Test for a numbered group. This includes groups called as a result of recursion. Note that whole-pattern recursion is coded as a recurse into group 0, so it won't be picked up here. Instead, we catch it when the OP_END is reached. */ if (number > 0) { md->capture_last = number; if (offset >= md->offset_max) md->offset_overflow = TRUE; else { md->offset_vector[offset] = md->offset_vector[md->offset_end - number]; md->offset_vector[offset+1] = eptr - md->start_subject; if (offset_top <= offset) offset_top = offset + 2; } /* Handle a recursively called group. Restore the offsets appropriately and continue from after the call. */ if (md->recursive != NULL && md->recursive->group_num == number) { recursion_info *rec = md->recursive; DPRINTF(("Recursion (%d) succeeded - continuing\n", number)); md->recursive = rec->prevrec; md->start_match = rec->save_start; memcpy(md->offset_vector, rec->offset_save, rec->saved_max * sizeof(int)); ecode = rec->after_call; ims = original_ims; break; } } } /* Reset the value of the ims flags, in case they got changed during the group. */ ims = original_ims; DPRINTF(("ims reset to %02lx\n", ims)); /* For a non-repeating ket, just continue at this level. This also happens for a repeating ket if no characters were matched in the group. This is the forcible breaking of infinite loops as implemented in Perl 5.005. If there is an options reset, it will get obeyed in the normal course of events. */ if (*ecode == OP_KET || eptr == saved_eptr) { ecode += 1 + LINK_SIZE; break; } /* The repeating kets try the rest of the pattern or restart from the preceding bracket, in the appropriate order. */ if (*ecode == OP_KETRMIN) { RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); } else /* OP_KETRMAX */ { RMATCH(rrc, eptr, prev, offset_top, md, ims, eptrb, match_isgroup); if (rrc != MATCH_NOMATCH) RRETURN(rrc); RMATCH(rrc, eptr, ecode + 1+LINK_SIZE, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); } } RRETURN(MATCH_NOMATCH); /* Start of subject unless notbol, or after internal newline if multiline */ case OP_CIRC: if (md->notbol && eptr == md->start_subject) RRETURN(MATCH_NOMATCH); if ((ims & PCRE_MULTILINE) != 0) { if (eptr != md->start_subject && eptr[-1] != NEWLINE) RRETURN(MATCH_NOMATCH); ecode++; break; } /* ... else fall through */ /* Start of subject assertion */ case OP_SOD: if (eptr != md->start_subject) RRETURN(MATCH_NOMATCH); ecode++; break; /* Start of match assertion */ case OP_SOM: if (eptr != md->start_subject + md->start_offset) RRETURN(MATCH_NOMATCH); ecode++; break; /* Assert before internal newline if multiline, or before a terminating newline unless endonly is set, else end of subject unless noteol is set. */ case OP_DOLL: if ((ims & PCRE_MULTILINE) != 0) { if (eptr < md->end_subject) { if (*eptr != NEWLINE) RRETURN(MATCH_NOMATCH); } else { if (md->noteol) RRETURN(MATCH_NOMATCH); } ecode++; break; } else { if (md->noteol) RRETURN(MATCH_NOMATCH); if (!md->endonly) { if (eptr < md->end_subject - 1 || (eptr == md->end_subject - 1 && *eptr != NEWLINE)) RRETURN(MATCH_NOMATCH); ecode++; break; } } /* ... else fall through */ /* End of subject assertion (\z) */ case OP_EOD: if (eptr < md->end_subject) RRETURN(MATCH_NOMATCH); ecode++; break; /* End of subject or ending \n assertion (\Z) */ case OP_EODN: if (eptr < md->end_subject - 1 || (eptr == md->end_subject - 1 && *eptr != NEWLINE)) RRETURN(MATCH_NOMATCH); ecode++; break; /* Word boundary assertions */ case OP_NOT_WORD_BOUNDARY: case OP_WORD_BOUNDARY: { /* Find out if the previous and current characters are "word" characters. It takes a bit more work in UTF-8 mode. Characters > 255 are assumed to be "non-word" characters. */ #ifdef SUPPORT_UTF8 if (md->utf8) { if (eptr == md->start_subject) prev_is_word = FALSE; else { lastptr = eptr - 1; while((*lastptr & 0xc0) == 0x80) lastptr--; GETCHAR(c, lastptr); prev_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; } if (eptr >= md->end_subject) cur_is_word = FALSE; else { GETCHAR(c, eptr); cur_is_word = c < 256 && (md->ctypes[c] & ctype_word) != 0; } } else #endif /* More streamlined when not in UTF-8 mode */ { prev_is_word = (eptr != md->start_subject) && ((md->ctypes[eptr[-1]] & ctype_word) != 0); cur_is_word = (eptr < md->end_subject) && ((md->ctypes[*eptr] & ctype_word) != 0); } /* Now see if the situation is what we want */ if ((*ecode++ == OP_WORD_BOUNDARY)? cur_is_word == prev_is_word : cur_is_word != prev_is_word) RRETURN(MATCH_NOMATCH); } break; /* Match a single character type; inline for speed */ case OP_ANY: if ((ims & PCRE_DOTALL) == 0 && eptr < md->end_subject && *eptr == NEWLINE) RRETURN(MATCH_NOMATCH); if (eptr++ >= md->end_subject) RRETURN(MATCH_NOMATCH); #ifdef SUPPORT_UTF8 if (md->utf8) while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; #endif ecode++; break; /* Match a single byte, even in UTF-8 mode. This opcode really does match any byte, even newline, independent of the setting of PCRE_DOTALL. */ case OP_ANYBYTE: if (eptr++ >= md->end_subject) RRETURN(MATCH_NOMATCH); ecode++; break; case OP_NOT_DIGIT: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINCTEST(c, eptr); if ( #ifdef SUPPORT_UTF8 c < 256 && #endif (md->ctypes[c] & ctype_digit) != 0 ) RRETURN(MATCH_NOMATCH); ecode++; break; case OP_DIGIT: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINCTEST(c, eptr); if ( #ifdef SUPPORT_UTF8 c >= 256 || #endif (md->ctypes[c] & ctype_digit) == 0 ) RRETURN(MATCH_NOMATCH); ecode++; break; case OP_NOT_WHITESPACE: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINCTEST(c, eptr); if ( #ifdef SUPPORT_UTF8 c < 256 && #endif (md->ctypes[c] & ctype_space) != 0 ) RRETURN(MATCH_NOMATCH); ecode++; break; case OP_WHITESPACE: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINCTEST(c, eptr); if ( #ifdef SUPPORT_UTF8 c >= 256 || #endif (md->ctypes[c] & ctype_space) == 0 ) RRETURN(MATCH_NOMATCH); ecode++; break; case OP_NOT_WORDCHAR: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINCTEST(c, eptr); if ( #ifdef SUPPORT_UTF8 c < 256 && #endif (md->ctypes[c] & ctype_word) != 0 ) RRETURN(MATCH_NOMATCH); ecode++; break; case OP_WORDCHAR: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINCTEST(c, eptr); if ( #ifdef SUPPORT_UTF8 c >= 256 || #endif (md->ctypes[c] & ctype_word) == 0 ) RRETURN(MATCH_NOMATCH); ecode++; break; /* Match a back reference, possibly repeatedly. Look past the end of the item to see if there is repeat information following. The code is similar to that for character classes, but repeated for efficiency. Then obey similar code to character type repeats - written out again for speed. However, if the referenced string is the empty string, always treat it as matched, any number of times (otherwise there could be infinite loops). */ case OP_REF: { offset = GET2(ecode, 1) << 1; /* Doubled ref number */ ecode += 3; /* Advance past item */ /* If the reference is unset, set the length to be longer than the amount of subject left; this ensures that every attempt at a match fails. We can't just fail here, because of the possibility of quantifiers with zero minima. */ length = (offset >= offset_top || md->offset_vector[offset] < 0)? md->end_subject - eptr + 1 : md->offset_vector[offset+1] - md->offset_vector[offset]; /* Set up for repetition, or handle the non-repeated case */ switch (*ecode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: c = *ecode++ - OP_CRSTAR; minimize = (c & 1) != 0; min = rep_min[c]; /* Pick up values from tables; */ max = rep_max[c]; /* zero for max => infinity */ if (max == 0) max = INT_MAX; break; case OP_CRRANGE: case OP_CRMINRANGE: minimize = (*ecode == OP_CRMINRANGE); min = GET2(ecode, 1); max = GET2(ecode, 3); if (max == 0) max = INT_MAX; ecode += 5; break; default: /* No repeat follows */ if (!match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); eptr += length; continue; /* With the main loop */ } /* If the length of the reference is zero, just continue with the main loop. */ if (length == 0) continue; /* First, ensure the minimum number of matches are present. We get back the length of the reference string explicitly rather than passing the address of eptr, so that eptr can be a register variable. */ for (i = 1; i <= min; i++) { if (!match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); eptr += length; } /* If min = max, continue at the same level without recursion. They are not both allowed to be zero. */ if (min == max) continue; /* If minimizing, keep trying and advancing the pointer */ if (minimize) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || !match_ref(offset, eptr, length, md, ims)) RRETURN(MATCH_NOMATCH); eptr += length; } /* Control never gets here */ } /* If maximizing, find the longest string and work backwards */ else { pp = eptr; for (i = min; i < max; i++) { if (!match_ref(offset, eptr, length, md, ims)) break; eptr += length; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); eptr -= length; } RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ /* Match a bit-mapped character class, possibly repeatedly. This op code is used when all the characters in the class have values in the range 0-255. The only difference between OP_CLASS and OP_NCLASS occurs when a data character outside the range is encountered. First, look past the end of the item to see if there is repeat information following. Then obey similar code to character type repeats - written out again for speed. */ case OP_NCLASS: case OP_CLASS: { data = ecode + 1; /* Save for matching */ ecode += 33; /* Advance past the item */ switch (*ecode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: c = *ecode++ - OP_CRSTAR; minimize = (c & 1) != 0; min = rep_min[c]; /* Pick up values from tables; */ max = rep_max[c]; /* zero for max => infinity */ if (max == 0) max = INT_MAX; break; case OP_CRRANGE: case OP_CRMINRANGE: minimize = (*ecode == OP_CRMINRANGE); min = GET2(ecode, 1); max = GET2(ecode, 3); if (max == 0) max = INT_MAX; ecode += 5; break; default: /* No repeat follows */ min = max = 1; break; } /* First, ensure the minimum number of matches are present. */ #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { for (i = 1; i <= min; i++) { if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINC(c, eptr); if (c > 255) { if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); } else { if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); } } } else #endif /* Not UTF-8 mode */ { for (i = 1; i <= min; i++) { if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); c = *eptr++; if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); } } /* If max == min we can continue with the main loop without the need to recurse. */ if (min == max) continue; /* If minimizing, keep testing the rest of the expression and advancing the pointer while it matches the class. */ if (minimize) { #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINC(c, eptr); if (c > 255) { if (op == OP_CLASS) RRETURN(MATCH_NOMATCH); } else { if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); } } } else #endif /* Not UTF-8 mode */ { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); c = *eptr++; if ((data[c/8] & (1 << (c&7))) == 0) RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ } /* If maximizing, find the longest possible run, then work backwards. */ else { pp = eptr; #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c > 255) { if (op == OP_CLASS) break; } else { if ((data[c/8] & (1 << (c&7))) == 0) break; } eptr += len; } for (;;) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (eptr-- == pp) break; /* Stop if tried at original pos */ BACKCHAR(eptr); } } else #endif /* Not UTF-8 mode */ { for (i = min; i < max; i++) { if (eptr >= md->end_subject) break; c = *eptr; if ((data[c/8] & (1 << (c&7))) == 0) break; eptr++; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); eptr--; if (rrc != MATCH_NOMATCH) RRETURN(rrc); } } RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ /* Match an extended character class. This opcode is encountered only in UTF-8 mode, because that's the only time it is compiled. */ #ifdef SUPPORT_UTF8 case OP_XCLASS: { data = ecode + 1 + LINK_SIZE; /* Save for matching */ ecode += GET(ecode, 1); /* Advance past the item */ switch (*ecode) { case OP_CRSTAR: case OP_CRMINSTAR: case OP_CRPLUS: case OP_CRMINPLUS: case OP_CRQUERY: case OP_CRMINQUERY: c = *ecode++ - OP_CRSTAR; minimize = (c & 1) != 0; min = rep_min[c]; /* Pick up values from tables; */ max = rep_max[c]; /* zero for max => infinity */ if (max == 0) max = INT_MAX; break; case OP_CRRANGE: case OP_CRMINRANGE: minimize = (*ecode == OP_CRMINRANGE); min = GET2(ecode, 1); max = GET2(ecode, 3); if (max == 0) max = INT_MAX; ecode += 5; break; default: /* No repeat follows */ min = max = 1; break; } /* First, ensure the minimum number of matches are present. */ for (i = 1; i <= min; i++) { if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINC(c, eptr); if (!match_xclass(c, data)) RRETURN(MATCH_NOMATCH); } /* If max == min we can continue with the main loop without the need to recurse. */ if (min == max) continue; /* If minimizing, keep testing the rest of the expression and advancing the pointer while it matches the class. */ if (minimize) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINC(c, eptr); if (!match_xclass(c, data)) RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } /* If maximizing, find the longest possible run, then work backwards. */ else { pp = eptr; for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (!match_xclass(c, data)) break; eptr += len; } for(;;) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (eptr-- == pp) break; /* Stop if tried at original pos */ BACKCHAR(eptr) } RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } #endif /* End of XCLASS */ /* Match a run of characters */ case OP_CHARS: { register int slen = ecode[1]; ecode += 2; #ifdef DEBUG /* Sigh. Some compilers never learn. */ if (eptr >= md->end_subject) printf("matching subject against pattern "); else { printf("matching subject "); pchars(eptr, slen, TRUE, md); printf(" against pattern "); } pchars(ecode, slen, FALSE, md); printf("\n"); #endif if (slen > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); if ((ims & PCRE_CASELESS) != 0) { while (slen-- > 0) if (md->lcc[*ecode++] != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); } else { while (slen-- > 0) if (*ecode++ != *eptr++) RRETURN(MATCH_NOMATCH); } } break; /* Match a single character repeatedly; different opcodes share code. */ case OP_EXACT: min = max = GET2(ecode, 1); ecode += 3; goto REPEATCHAR; case OP_UPTO: case OP_MINUPTO: min = 0; max = GET2(ecode, 1); minimize = *ecode == OP_MINUPTO; ecode += 3; goto REPEATCHAR; case OP_STAR: case OP_MINSTAR: case OP_PLUS: case OP_MINPLUS: case OP_QUERY: case OP_MINQUERY: c = *ecode++ - OP_STAR; minimize = (c & 1) != 0; min = rep_min[c]; /* Pick up values from tables; */ max = rep_max[c]; /* zero for max => infinity */ if (max == 0) max = INT_MAX; /* Common code for all repeated single-character matches. We can give up quickly if there are fewer than the minimum number of characters left in the subject. */ REPEATCHAR: #ifdef SUPPORT_UTF8 if (md->utf8) { length = 1; charptr = ecode; GETCHARLEN(fc, ecode, length); if (min * length > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); ecode += length; /* Handle multibyte character matching specially here. There is no support for any kind of casing for multibyte characters. */ if (length > 1) { for (i = 1; i <= min; i++) { if (memcmp(eptr, charptr, length) != 0) RRETURN(MATCH_NOMATCH); eptr += length; } if (min == max) continue; if (minimize) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject || memcmp(eptr, charptr, length) != 0) RRETURN(MATCH_NOMATCH); eptr += length; } /* Control never gets here */ } else { pp = eptr; for (i = min; i < max; i++) { if (eptr > md->end_subject - length || memcmp(eptr, charptr, length) != 0) break; eptr += length; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); eptr -= length; } RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } /* If the length of a UTF-8 character is 1, we fall through here, and obey the code as for non-UTF-8 characters below, though in this case the value of fc will always be < 128. */ } else #endif /* When not in UTF-8 mode, load a single-byte character. */ { if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); fc = *ecode++; } /* The value of fc at this point is always less than 256, though we may or may not be in UTF-8 mode. The code is duplicated for the caseless and caseful cases, for speed, since matching characters is likely to be quite common. First, ensure the minimum number of matches are present. If min = max, continue at the same level without recursing. Otherwise, if minimizing, keep trying the rest of the expression and advancing one matching character if failing, up to the maximum. Alternatively, if maximizing, find the maximum number of characters and work backwards. */ DPRINTF(("matching %c{%d,%d} against subject %.*s\n", fc, min, max, max, eptr)); if ((ims & PCRE_CASELESS) != 0) { fc = md->lcc[fc]; for (i = 1; i <= min; i++) if (fc != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); if (min == max) continue; if (minimize) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject || fc != md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } else { pp = eptr; for (i = min; i < max; i++) { if (eptr >= md->end_subject || fc != md->lcc[*eptr]) break; eptr++; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); eptr--; if (rrc != MATCH_NOMATCH) RRETURN(rrc); } RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } /* Caseful comparisons (includes all multi-byte characters) */ else { for (i = 1; i <= min; i++) if (fc != *eptr++) RRETURN(MATCH_NOMATCH); if (min == max) continue; if (minimize) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject || fc != *eptr++) RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } else { pp = eptr; for (i = min; i < max; i++) { if (eptr >= md->end_subject || fc != *eptr) break; eptr++; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); eptr--; if (rrc != MATCH_NOMATCH) RRETURN(rrc); } RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ /* Match a negated single one-byte character. The character we are checking can be multibyte. */ case OP_NOT: if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); ecode++; GETCHARINCTEST(c, eptr); if ((ims & PCRE_CASELESS) != 0) { #ifdef SUPPORT_UTF8 if (c < 256) #endif c = md->lcc[c]; if (md->lcc[*ecode++] == c) RRETURN(MATCH_NOMATCH); } else { if (*ecode++ == c) RRETURN(MATCH_NOMATCH); } break; /* Match a negated single one-byte character repeatedly. This is almost a repeat of the code for a repeated single character, but I haven't found a nice way of commoning these up that doesn't require a test of the positive/negative option for each character match. Maybe that wouldn't add very much to the time taken, but character matching *is* what this is all about... */ case OP_NOTEXACT: min = max = GET2(ecode, 1); ecode += 3; goto REPEATNOTCHAR; case OP_NOTUPTO: case OP_NOTMINUPTO: min = 0; max = GET2(ecode, 1); minimize = *ecode == OP_NOTMINUPTO; ecode += 3; goto REPEATNOTCHAR; case OP_NOTSTAR: case OP_NOTMINSTAR: case OP_NOTPLUS: case OP_NOTMINPLUS: case OP_NOTQUERY: case OP_NOTMINQUERY: c = *ecode++ - OP_NOTSTAR; minimize = (c & 1) != 0; min = rep_min[c]; /* Pick up values from tables; */ max = rep_max[c]; /* zero for max => infinity */ if (max == 0) max = INT_MAX; /* Common code for all repeated single-character (less than 255) matches. We can give up quickly if there are fewer than the minimum number of characters left in the subject. */ REPEATNOTCHAR: if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); fc = *ecode++; /* The code is duplicated for the caseless and caseful cases, for speed, since matching characters is likely to be quite common. First, ensure the minimum number of matches are present. If min = max, continue at the same level without recursing. Otherwise, if minimizing, keep trying the rest of the expression and advancing one matching character if failing, up to the maximum. Alternatively, if maximizing, find the maximum number of characters and work backwards. */ DPRINTF(("negative matching %c{%d,%d} against subject %.*s\n", fc, min, max, max, eptr)); if ((ims & PCRE_CASELESS) != 0) { fc = md->lcc[fc]; #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { register int d; for (i = 1; i <= min; i++) { GETCHARINC(d, eptr); if (d < 256) d = md->lcc[d]; if (fc == d) RRETURN(MATCH_NOMATCH); } } else #endif /* Not UTF-8 mode */ { for (i = 1; i <= min; i++) if (fc == md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); } if (min == max) continue; if (minimize) { #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { register int d; for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); GETCHARINC(d, eptr); if (d < 256) d = md->lcc[d]; if (fi >= max || eptr >= md->end_subject || fc == d) RRETURN(MATCH_NOMATCH); } } else #endif /* Not UTF-8 mode */ { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject || fc == md->lcc[*eptr++]) RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ } /* Maximize case */ else { pp = eptr; #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { register int d; for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(d, eptr, len); if (d < 256) d = md->lcc[d]; if (fc == d) break; eptr += len; } for(;;) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (eptr-- == pp) break; /* Stop if tried at original pos */ BACKCHAR(eptr); } } else #endif /* Not UTF-8 mode */ { for (i = min; i < max; i++) { if (eptr >= md->end_subject || fc == md->lcc[*eptr]) break; eptr++; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); eptr--; } } RRETURN(MATCH_NOMATCH); } /* Control never gets here */ } /* Caseful comparisons */ else { #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { register int d; for (i = 1; i <= min; i++) { GETCHARINC(d, eptr); if (fc == d) RRETURN(MATCH_NOMATCH); } } else #endif /* Not UTF-8 mode */ { for (i = 1; i <= min; i++) if (fc == *eptr++) RRETURN(MATCH_NOMATCH); } if (min == max) continue; if (minimize) { #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { register int d; for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); GETCHARINC(d, eptr); if (fi >= max || eptr >= md->end_subject || fc == d) RRETURN(MATCH_NOMATCH); } } else #endif /* Not UTF-8 mode */ { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject || fc == *eptr++) RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ } /* Maximize case */ else { pp = eptr; #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { register int d; for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(d, eptr, len); if (fc == d) break; eptr += len; } for(;;) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (eptr-- == pp) break; /* Stop if tried at original pos */ BACKCHAR(eptr); } } else #endif /* Not UTF-8 mode */ { for (i = min; i < max; i++) { if (eptr >= md->end_subject || fc == *eptr) break; eptr++; } while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); eptr--; } } RRETURN(MATCH_NOMATCH); } } /* Control never gets here */ /* Match a single character type repeatedly; several different opcodes share code. This is very similar to the code for single characters, but we repeat it in the interests of efficiency. */ case OP_TYPEEXACT: min = max = GET2(ecode, 1); minimize = TRUE; ecode += 3; goto REPEATTYPE; case OP_TYPEUPTO: case OP_TYPEMINUPTO: min = 0; max = GET2(ecode, 1); minimize = *ecode == OP_TYPEMINUPTO; ecode += 3; goto REPEATTYPE; case OP_TYPESTAR: case OP_TYPEMINSTAR: case OP_TYPEPLUS: case OP_TYPEMINPLUS: case OP_TYPEQUERY: case OP_TYPEMINQUERY: c = *ecode++ - OP_TYPESTAR; minimize = (c & 1) != 0; min = rep_min[c]; /* Pick up values from tables; */ max = rep_max[c]; /* zero for max => infinity */ if (max == 0) max = INT_MAX; /* Common code for all repeated single character type matches. Note that in UTF-8 mode, '.' matches a character of any length, but for the other character types, the valid characters are all one-byte long. */ REPEATTYPE: ctype = *ecode++; /* Code for the character type */ /* First, ensure the minimum number of matches are present. Use inline code for maximizing the speed, and do the type test once at the start (i.e. keep it out of the loop). Also we can test that there are at least the minimum number of bytes before we start. This isn't as effective in UTF-8 mode, but it does no harm. Separate the UTF-8 code completely as that is tidier. */ if (min > md->end_subject - eptr) RRETURN(MATCH_NOMATCH); if (min > 0) { #ifdef SUPPORT_UTF8 if (md->utf8) switch(ctype) { case OP_ANY: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject || (*eptr++ == NEWLINE && (ims & PCRE_DOTALL) == 0)) RRETURN(MATCH_NOMATCH); while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; } break; case OP_ANYBYTE: eptr += min; break; case OP_NOT_DIGIT: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINC(c, eptr); if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); } break; case OP_DIGIT: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject || *eptr >= 128 || (md->ctypes[*eptr++] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); /* No need to skip more bytes - we know it's a 1-byte character */ } break; case OP_NOT_WHITESPACE: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject || (*eptr < 128 && (md->ctypes[*eptr++] & ctype_space) != 0)) RRETURN(MATCH_NOMATCH); while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; } break; case OP_WHITESPACE: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject || *eptr >= 128 || (md->ctypes[*eptr++] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); /* No need to skip more bytes - we know it's a 1-byte character */ } break; case OP_NOT_WORDCHAR: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject || (*eptr < 128 && (md->ctypes[*eptr++] & ctype_word) != 0)) RRETURN(MATCH_NOMATCH); while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; } break; case OP_WORDCHAR: for (i = 1; i <= min; i++) { if (eptr >= md->end_subject || *eptr >= 128 || (md->ctypes[*eptr++] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); /* No need to skip more bytes - we know it's a 1-byte character */ } break; } else #endif /* Code for the non-UTF-8 case for minimum matching */ switch(ctype) { case OP_ANY: if ((ims & PCRE_DOTALL) == 0) { for (i = 1; i <= min; i++) if (*eptr++ == NEWLINE) RRETURN(MATCH_NOMATCH); } else eptr += min; break; case OP_ANYBYTE: eptr += min; break; case OP_NOT_DIGIT: for (i = 1; i <= min; i++) if ((md->ctypes[*eptr++] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); break; case OP_DIGIT: for (i = 1; i <= min; i++) if ((md->ctypes[*eptr++] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); break; case OP_NOT_WHITESPACE: for (i = 1; i <= min; i++) if ((md->ctypes[*eptr++] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); break; case OP_WHITESPACE: for (i = 1; i <= min; i++) if ((md->ctypes[*eptr++] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); break; case OP_NOT_WORDCHAR: for (i = 1; i <= min; i++) if ((md->ctypes[*eptr++] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); break; case OP_WORDCHAR: for (i = 1; i <= min; i++) if ((md->ctypes[*eptr++] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); break; } } /* If min = max, continue at the same level without recursing */ if (min == max) continue; /* If minimizing, we have to test the rest of the pattern before each subsequent match. Again, separate the UTF-8 case for speed. */ if (minimize) { #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); GETCHARINC(c, eptr); switch(ctype) { case OP_ANY: if ((ims & PCRE_DOTALL) == 0 && c == NEWLINE) RRETURN(MATCH_NOMATCH); break; case OP_ANYBYTE: break; case OP_NOT_DIGIT: if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); break; case OP_DIGIT: if (c >= 256 || (md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); break; case OP_NOT_WHITESPACE: if (c < 256 && (md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); break; case OP_WHITESPACE: if (c >= 256 || (md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); break; case OP_NOT_WORDCHAR: if (c < 256 && (md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); break; case OP_WORDCHAR: if (c >= 256 && (md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); break; } } } else #endif /* Not UTF-8 mode */ { for (fi = min;; fi++) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (fi >= max || eptr >= md->end_subject) RRETURN(MATCH_NOMATCH); c = *eptr++; switch(ctype) { case OP_ANY: if ((ims & PCRE_DOTALL) == 0 && c == NEWLINE) RRETURN(MATCH_NOMATCH); break; case OP_ANYBYTE: break; case OP_NOT_DIGIT: if ((md->ctypes[c] & ctype_digit) != 0) RRETURN(MATCH_NOMATCH); break; case OP_DIGIT: if ((md->ctypes[c] & ctype_digit) == 0) RRETURN(MATCH_NOMATCH); break; case OP_NOT_WHITESPACE: if ((md->ctypes[c] & ctype_space) != 0) RRETURN(MATCH_NOMATCH); break; case OP_WHITESPACE: if ((md->ctypes[c] & ctype_space) == 0) RRETURN(MATCH_NOMATCH); break; case OP_NOT_WORDCHAR: if ((md->ctypes[c] & ctype_word) != 0) RRETURN(MATCH_NOMATCH); break; case OP_WORDCHAR: if ((md->ctypes[c] & ctype_word) == 0) RRETURN(MATCH_NOMATCH); break; } } } /* Control never gets here */ } /* If maximizing it is worth using inline code for speed, doing the type test once at the start (i.e. keep it out of the loop). Again, keep the UTF-8 stuff separate. */ else { pp = eptr; #ifdef SUPPORT_UTF8 /* UTF-8 mode */ if (md->utf8) { switch(ctype) { case OP_ANY: /* Special code is required for UTF8, but when the maximum is unlimited we don't need it, so we repeat the non-UTF8 code. This is probably worth it, because .* is quite a common idiom. */ if (max < INT_MAX) { if ((ims & PCRE_DOTALL) == 0) { for (i = min; i < max; i++) { if (eptr >= md->end_subject || *eptr == NEWLINE) break; eptr++; while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; } } else { for (i = min; i < max; i++) { eptr++; while (eptr < md->end_subject && (*eptr & 0xc0) == 0x80) eptr++; } } } /* Handle unlimited UTF-8 repeat */ else { if ((ims & PCRE_DOTALL) == 0) { for (i = min; i < max; i++) { if (eptr >= md->end_subject || *eptr == NEWLINE) break; eptr++; } break; } else { c = max - min; if (c > md->end_subject - eptr) c = md->end_subject - eptr; eptr += c; } } break; /* The byte case is the same as non-UTF8 */ case OP_ANYBYTE: c = max - min; if (c > md->end_subject - eptr) c = md->end_subject - eptr; eptr += c; break; case OP_NOT_DIGIT: for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c < 256 && (md->ctypes[c] & ctype_digit) != 0) break; eptr+= len; } break; case OP_DIGIT: for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c >= 256 ||(md->ctypes[c] & ctype_digit) == 0) break; eptr+= len; } break; case OP_NOT_WHITESPACE: for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c < 256 && (md->ctypes[c] & ctype_space) != 0) break; eptr+= len; } break; case OP_WHITESPACE: for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c >= 256 ||(md->ctypes[c] & ctype_space) == 0) break; eptr+= len; } break; case OP_NOT_WORDCHAR: for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c < 256 && (md->ctypes[c] & ctype_word) != 0) break; eptr+= len; } break; case OP_WORDCHAR: for (i = min; i < max; i++) { int len = 1; if (eptr >= md->end_subject) break; GETCHARLEN(c, eptr, len); if (c >= 256 || (md->ctypes[c] & ctype_word) == 0) break; eptr+= len; } break; } /* eptr is now past the end of the maximum run */ for(;;) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); if (rrc != MATCH_NOMATCH) RRETURN(rrc); if (eptr-- == pp) break; /* Stop if tried at original pos */ BACKCHAR(eptr); } } else #endif /* Not UTF-8 mode */ { switch(ctype) { case OP_ANY: if ((ims & PCRE_DOTALL) == 0) { for (i = min; i < max; i++) { if (eptr >= md->end_subject || *eptr == NEWLINE) break; eptr++; } break; } /* For DOTALL case, fall through and treat as \C */ case OP_ANYBYTE: c = max - min; if (c > md->end_subject - eptr) c = md->end_subject - eptr; eptr += c; break; case OP_NOT_DIGIT: for (i = min; i < max; i++) { if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_digit) != 0) break; eptr++; } break; case OP_DIGIT: for (i = min; i < max; i++) { if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_digit) == 0) break; eptr++; } break; case OP_NOT_WHITESPACE: for (i = min; i < max; i++) { if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_space) != 0) break; eptr++; } break; case OP_WHITESPACE: for (i = min; i < max; i++) { if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_space) == 0) break; eptr++; } break; case OP_NOT_WORDCHAR: for (i = min; i < max; i++) { if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_word) != 0) break; eptr++; } break; case OP_WORDCHAR: for (i = min; i < max; i++) { if (eptr >= md->end_subject || (md->ctypes[*eptr] & ctype_word) == 0) break; eptr++; } break; } /* eptr is now past the end of the maximum run */ while (eptr >= pp) { RMATCH(rrc, eptr, ecode, offset_top, md, ims, eptrb, 0); eptr--; if (rrc != MATCH_NOMATCH) RRETURN(rrc); } } /* Get here if we can't make it match with any permitted repetitions */ RRETURN(MATCH_NOMATCH); } /* Control never gets here */ /* There's been some horrible disaster. Since all codes > OP_BRA are for capturing brackets, and there shouldn't be any gaps between 0 and OP_BRA, arrival here can only mean there is something seriously wrong in the code above or the OP_xxx definitions. */ default: DPRINTF(("Unknown opcode %d\n", *ecode)); RRETURN(PCRE_ERROR_UNKNOWN_NODE); } /* Do not stick any code in here without much thought; it is assumed that "continue" in the code above comes out to here to repeat the main loop. */ } /* End of main loop */ /* Control never reaches here */ } /*************************************************************************** **************************************************************************** RECURSION IN THE match() FUNCTION Undefine all the macros that were defined above to handle this. */ #ifdef NO_RECURSE #undef eptr #undef ecode #undef offset_top #undef ims #undef eptrb #undef flags #undef callpat #undef charptr #undef data #undef lastptr #undef next #undef pp #undef prev #undef saved_eptr #undef new_recursive #undef cur_is_word #undef condition #undef minimize #undef prev_is_word #undef original_ims #undef ctype #undef length #undef max #undef min #undef number #undef offset #undef op #undef save_capture_last #undef save_offset1 #undef save_offset2 #undef save_offset3 #undef stacksave #undef newptrb #endif /* These two are defined as macros in both cases */ #undef fc #undef fi /*************************************************************************** ***************************************************************************/ /************************************************* * Execute a Regular Expression * *************************************************/ /* This function applies a compiled re to a subject string and picks out portions of the string if it matches. Two elements in the vector are set for each substring: the offsets to the start and end of the substring. Arguments: external_re points to the compiled expression extra_data points to extra data or is NULL subject points to the subject string length length of subject string (may contain binary zeros) start_offset where to start in the subject string options option bits offsets points to a vector of ints to be filled in with offsets offsetcount the number of elements in the vector Returns: > 0 => success; value is the number of elements filled in = 0 => success, but offsets is not big enough -1 => failed to match < -1 => some kind of unexpected problem */ EXPORT int pcre_exec(const pcre *external_re, const pcre_extra *extra_data, const char *subject, int length, int start_offset, int options, int *offsets, int offsetcount) { int rc, resetcount, ocount; int first_byte = -1; int req_byte = -1; int req_byte2 = -1; unsigned long int ims = 0; BOOL using_temporary_offsets = FALSE; BOOL anchored; BOOL startline; BOOL first_byte_caseless = FALSE; BOOL req_byte_caseless = FALSE; match_data match_block; const uschar *start_bits = NULL; const uschar *start_match = (const uschar *)subject + start_offset; const uschar *end_subject; const uschar *req_byte_ptr = start_match - 1; const pcre_study_data *study; const real_pcre *re = (const real_pcre *)external_re; /* Plausibility checks */ if ((options & ~PUBLIC_EXEC_OPTIONS) != 0) return PCRE_ERROR_BADOPTION; if (re == NULL || subject == NULL || (offsets == NULL && offsetcount > 0)) return PCRE_ERROR_NULL; /* Fish out the optional data from the extra_data structure, first setting the default values. */ study = NULL; match_block.match_limit = MATCH_LIMIT; match_block.callout_data = NULL; if (extra_data != NULL) { register unsigned int flags = extra_data->flags; if ((flags & PCRE_EXTRA_STUDY_DATA) != 0) study = (const pcre_study_data *)extra_data->study_data; if ((flags & PCRE_EXTRA_MATCH_LIMIT) != 0) match_block.match_limit = extra_data->match_limit; if ((flags & PCRE_EXTRA_CALLOUT_DATA) != 0) match_block.callout_data = extra_data->callout_data; } /* Now we have re supposedly pointing to the regex */ if (re->magic_number != MAGIC_NUMBER) return PCRE_ERROR_BADMAGIC; anchored = ((re->options | options) & PCRE_ANCHORED) != 0; startline = (re->options & PCRE_STARTLINE) != 0; match_block.start_code = (const uschar *)re + sizeof(real_pcre) + re->name_count * re->name_entry_size; match_block.start_subject = (const uschar *)subject; match_block.start_offset = start_offset; match_block.end_subject = match_block.start_subject + length; end_subject = match_block.end_subject; match_block.endonly = (re->options & PCRE_DOLLAR_ENDONLY) != 0; match_block.utf8 = (re->options & PCRE_UTF8) != 0; match_block.notbol = (options & PCRE_NOTBOL) != 0; match_block.noteol = (options & PCRE_NOTEOL) != 0; match_block.notempty = (options & PCRE_NOTEMPTY) != 0; match_block.recursive = NULL; /* No recursion at top level */ match_block.lcc = re->tables + lcc_offset; match_block.ctypes = re->tables + ctypes_offset; /* Check a UTF-8 string if required. Unfortunately there's no way of passing back the character offset. */ #ifdef SUPPORT_UTF8 if (match_block.utf8 && (options & PCRE_NO_UTF8_CHECK) == 0) { if (valid_utf8((uschar *)subject, length) >= 0) return PCRE_ERROR_BADUTF8; if (start_offset > 0 && start_offset < length) { int tb = ((uschar *)subject)[start_offset]; if (tb > 127) { tb &= 0xc0; if (tb != 0 && tb != 0xc0) return PCRE_ERROR_BADUTF8_OFFSET; } } } #endif /* The ims options can vary during the matching as a result of the presence of (?ims) items in the pattern. They are kept in a local variable so that restoring at the exit of a group is easy. */ ims = re->options & (PCRE_CASELESS|PCRE_MULTILINE|PCRE_DOTALL); /* If the expression has got more back references than the offsets supplied can hold, we get a temporary bit of working store to use during the matching. Otherwise, we can use the vector supplied, rounding down its size to a multiple of 3. */ ocount = offsetcount - (offsetcount % 3); if (re->top_backref > 0 && re->top_backref >= ocount/3) { ocount = re->top_backref * 3 + 3; match_block.offset_vector = (int *)(pcre_malloc)(ocount * sizeof(int)); if (match_block.offset_vector == NULL) return PCRE_ERROR_NOMEMORY; using_temporary_offsets = TRUE; DPRINTF(("Got memory to hold back references\n")); } else match_block.offset_vector = offsets; match_block.offset_end = ocount; match_block.offset_max = (2*ocount)/3; match_block.offset_overflow = FALSE; match_block.capture_last = -1; /* Compute the minimum number of offsets that we need to reset each time. Doing this makes a huge difference to execution time when there aren't many brackets in the pattern. */ resetcount = 2 + re->top_bracket * 2; if (resetcount > offsetcount) resetcount = ocount; /* Reset the working variable associated with each extraction. These should never be used unless previously set, but they get saved and restored, and so we initialize them to avoid reading uninitialized locations. */ if (match_block.offset_vector != NULL) { register int *iptr = match_block.offset_vector + ocount; register int *iend = iptr - resetcount/2 + 1; while (--iptr >= iend) *iptr = -1; } /* Set up the first character to match, if available. The first_byte value is never set for an anchored regular expression, but the anchoring may be forced at run time, so we have to test for anchoring. The first char may be unset for an unanchored pattern, of course. If there's no first char and the pattern was studied, there may be a bitmap of possible first characters. */ if (!anchored) { if ((re->options & PCRE_FIRSTSET) != 0) { first_byte = re->first_byte & 255; if ((first_byte_caseless = ((re->first_byte & REQ_CASELESS) != 0)) == TRUE) first_byte = match_block.lcc[first_byte]; } else if (!startline && study != NULL && (study->options & PCRE_STUDY_MAPPED) != 0) start_bits = study->start_bits; } /* For anchored or unanchored matches, there may be a "last known required character" set. */ if ((re->options & PCRE_REQCHSET) != 0) { req_byte = re->req_byte & 255; req_byte_caseless = (re->req_byte & REQ_CASELESS) != 0; req_byte2 = (re->tables + fcc_offset)[req_byte]; /* case flipped */ } /* Loop for handling unanchored repeated matching attempts; for anchored regexs the loop runs just once. */ do { register int *iptr = match_block.offset_vector; register int *iend = iptr + resetcount; /* Reset the maximum number of extractions we might see. */ while (iptr < iend) *iptr++ = -1; /* Advance to a unique first char if possible */ if (first_byte >= 0) { if (first_byte_caseless) while (start_match < end_subject && match_block.lcc[*start_match] != first_byte) start_match++; else while (start_match < end_subject && *start_match != first_byte) start_match++; } /* Or to just after \n for a multiline match if possible */ else if (startline) { if (start_match > match_block.start_subject + start_offset) { while (start_match < end_subject && start_match[-1] != NEWLINE) start_match++; } } /* Or to a non-unique first char after study */ else if (start_bits != NULL) { while (start_match < end_subject) { register int c = *start_match; if ((start_bits[c/8] & (1 << (c&7))) == 0) start_match++; else break; } } #ifdef DEBUG /* Sigh. Some compilers never learn. */ printf(">>>> Match against: "); pchars(start_match, end_subject - start_match, TRUE, &match_block); printf("\n"); #endif /* If req_byte is set, we know that that character must appear in the subject for the match to succeed. If the first character is set, req_byte must be later in the subject; otherwise the test starts at the match point. This optimization can save a huge amount of backtracking in patterns with nested unlimited repeats that aren't going to match. Writing separate code for cased/caseless versions makes it go faster, as does using an autoincrement and backing off on a match. HOWEVER: when the subject string is very, very long, searching to its end can take a long time, and give bad performance on quite ordinary patterns. This showed up when somebody was matching /^C/ on a 32-megabyte string... so we don't do this when the string is sufficiently long. */ if (req_byte >= 0 && end_subject - start_match < REQ_BYTE_MAX) { register const uschar *p = start_match + ((first_byte >= 0)? 1 : 0); /* We don't need to repeat the search if we haven't yet reached the place we found it at last time. */ if (p > req_byte_ptr) { if (req_byte_caseless) { while (p < end_subject) { register int pp = *p++; if (pp == req_byte || pp == req_byte2) { p--; break; } } } else { while (p < end_subject) { if (*p++ == req_byte) { p--; break; } } } /* If we can't find the required character, break the matching loop */ if (p >= end_subject) break; /* If we have found the required character, save the point where we found it, so that we don't search again next time round the loop if the start hasn't passed this character yet. */ req_byte_ptr = p; } } /* When a match occurs, substrings will be set for all internal extractions; we just need to set up the whole thing as substring 0 before returning. If there were too many extractions, set the return code to zero. In the case where we had to get some local store to hold offsets for backreferences, copy those back references that we can. In this case there need not be overflow if certain parts of the pattern were not used. */ match_block.start_match = start_match; match_block.match_call_count = 0; rc = match(start_match, match_block.start_code, 2, &match_block, ims, NULL, match_isgroup); if (rc == MATCH_NOMATCH) { start_match++; #ifdef SUPPORT_UTF8 if (match_block.utf8) while((*start_match & 0xc0) == 0x80) start_match++; #endif continue; } if (rc != MATCH_MATCH) { DPRINTF((">>>> error: returning %d\n", rc)); return rc; } /* We have a match! Copy the offset information from temporary store if necessary */ if (using_temporary_offsets) { if (offsetcount >= 4) { memcpy(offsets + 2, match_block.offset_vector + 2, (offsetcount - 2) * sizeof(int)); DPRINTF(("Copied offsets from temporary memory\n")); } if (match_block.end_offset_top > offsetcount) match_block.offset_overflow = TRUE; DPRINTF(("Freeing temporary memory\n")); (pcre_free)(match_block.offset_vector); } rc = match_block.offset_overflow? 0 : match_block.end_offset_top/2; if (offsetcount < 2) rc = 0; else { offsets[0] = start_match - match_block.start_subject; offsets[1] = match_block.end_match_ptr - match_block.start_subject; } DPRINTF((">>>> returning %d\n", rc)); return rc; } /* This "while" is the end of the "do" above */ while (!anchored && start_match <= end_subject); if (using_temporary_offsets) { DPRINTF(("Freeing temporary memory\n")); (pcre_free)(match_block.offset_vector); } DPRINTF((">>>> returning PCRE_ERROR_NOMATCH\n")); return PCRE_ERROR_NOMATCH; } /* End of pcre.c */ avenger-0.8.5/libasync/stllike.h0000644000175000017500000000654111221237220013516 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _STL_LIKE_H_ #define _STL_LIKE_H_ #ifndef USE_STL /* misc stuff */ #undef min template inline const T &min (const T &a, const T &b) { return b < a ? b : a; } #undef max template inline const T &max (const T &a, const T &b) { return a < b ? b : a; } #else /* USE_STL */ #include #endif /* USE_STL */ template inline R implicit_cast (R r) { return r; } /* * The remaining code is additionally covered by this copyright: * * Copyright (c) 1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ template class auto_ptr { private: T* M_ptr; public: typedef T element_type; explicit auto_ptr (T *p = 0) : M_ptr (p) {} auto_ptr (auto_ptr &a) : M_ptr (a.release ()) {} template auto_ptr (auto_ptr &a) : M_ptr (a.release ()) {} auto_ptr &operator= (auto_ptr& a) { if (&a != this) { delete M_ptr; M_ptr = a.release(); } return *this; } template auto_ptr &operator= (auto_ptr &a) { if (a.get() != this->get()) { delete M_ptr; M_ptr = a.release(); } return *this; } ~auto_ptr () { delete M_ptr; } T &operator* () const { return *M_ptr; } T *operator-> () const { return M_ptr; } T *get () const { return M_ptr; } T *release () { T *tmp = M_ptr; M_ptr = 0; return tmp; } void reset (T *p = 0) { delete M_ptr; M_ptr = p; } #if 0 // I don't understand the following // According to the C++ standard, these conversions are required. Most // present-day compilers, however, do not enforce that requirement---and, // in fact, most present-day compilers do not support the language // features that these conversions rely on. private: template struct auto_ptr_ref { U *M_ptr; auto_ptr_ref (U *p) : M_ptr (p) {} }; public: auto_ptr (auto_ptr_ref ref) : M_ptr (ref.M_ptr) {} template operator auto_ptr_ref () { return auto_ptr_ref (this.release ()); } template operator auto_ptr () { return auto_ptr (this->release ()) } #endif /* 0 */ }; #endif /* !_STL_LIKE_H_ */ avenger-0.8.5/libasync/dnsimpl.h0000644000175000017500000001333012260427602013520 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 2003 David Mazieres (dm@uun.org) * * 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 _ASYNC_DNSIMPL_H_ #define _ASYNC_DNSIMPL_H_ 1 #include "dnsparse.h" #include "ihash.h" #include "backoff.h" /* resolvconf.C */ struct parsed_resolv_conf { vec searchlist; vec resolvers; vec resolvers_sa_len; }; str satostr (const sockaddr_storage *sa); bool strtosa (sockaddr_storage *ss, const char *p); void show_resolv_conf (const parsed_resolv_conf &rc); void parse_resolv_conf (parsed_resolv_conf *out, const str &path, bool v4only = true); #if HAVE___RES_NINIT #define NEWRES 1 #endif /* HAVE___RES_NINIT */ class resolver; class dnsreq { int ntries; int srchno; public: resolver *const resp; bool usetcp; private: bool constructed; bool intable; protected: void remove (); public: int error; u_int16_t id; // DNS query ID str basename; // Name for which to search str name; // Name for which to query u_int16_t type; // Type of query (T_A, T_PTR, etc.) ihash_entry hlink; // Per-id hash table link tmoq_entry tlink; // Retransmit queue link dnsreq (resolver *, str, u_int16_t, bool search = false); virtual ~dnsreq (); void start (bool); void xmit (int = 0); virtual void readreply (dnsparse *) = 0; void timeout (); void fail (int); }; class dnsreq_a : public dnsreq { bool checkaddr; // Non-zero when arr_addr must be checked in_addr addr; // Adress of inverse queries (for checking) cbhent cb; // Callback for hostbyname/addr dnsreq_a (); public: dnsreq_a (resolver *rp, str n, cbhent c, bool s = false) : dnsreq (rp, n, T_A, s), checkaddr (false), cb (c) {} dnsreq_a (resolver *rp, str n, cbhent c, const in_addr &a) : dnsreq (rp, n, T_A), checkaddr (true), addr (a), cb (c) {} void readreply (dnsparse *); }; class dnsreq_mx : public dnsreq { cbmxlist cb; dnsreq_mx (); public: dnsreq_mx (resolver *rp, str n, cbmxlist c, bool s) : dnsreq (rp, n, T_MX, s), cb (c) {} void readreply (dnsparse *); }; class dnsreq_srv : public dnsreq { cbsrvlist cb; dnsreq_srv (); public: dnsreq_srv (resolver *rp, str n, cbsrvlist c, bool s) : dnsreq (rp, n, T_SRV, s), cb (c) {} void readreply (dnsparse *); }; class dnsreq_ptr : public dnsreq { in_addr addr; cbhent cb; // Callback for hostbyname/addr int napending; vec vnames; vec vrfyv; static void maybe_push (vec *sv, const char *s); public: static str inaddr_arpa (in_addr); dnsreq_ptr (resolver *rp, in_addr a, cbhent c) : dnsreq (rp, inaddr_arpa (a), T_PTR), addr (a), cb (c) {} ~dnsreq_ptr (); void readreply (dnsparse *); void readvrfy (int i, ptr h, int err); }; class dnsreq_txt : public dnsreq { cbtxtlist cb; public: dnsreq_txt (resolver *rp, str n, cbtxtlist c, bool s = false) : dnsreq (rp, n, T_TXT, s), cb (c) {} void readreply (dnsparse *); }; class dnssock { public: typedef callback::ref cb_t; protected: cb_t cb; ref destroyed; public: const bool reliable; dnssock (bool r, cb_t c) : cb (c), destroyed (New refcounted (false)), reliable (r) {} virtual ~dnssock () { *destroyed = false; } virtual void sendpkt (const u_char *pkt, size_t size) = 0; }; class dnssock_udp : public dnssock { int fd; void rcb (); public: dnssock_udp (int f, cb_t cb); ~dnssock_udp (); void sendpkt (const u_char *pkt, size_t size); }; class dnssock_tcp : public dnssock { int fd; bool write_ok; dnstcppkt tcpstate; void rcb (); void wcb (bool selected = false); public: dnssock_tcp (int f, cb_t cb); ~dnssock_tcp (); void sendpkt (const u_char *pkt, size_t size); }; class resolver { protected: ptr udpsock; ptr tcpsock; int nbump; // # of bumpsocks since last good reply const sockaddr *addr; socklen_t addrlen; dnsreq *udpcheck_req; #if NEWRES struct __res_state res; #endif /* NEWRES */ virtual bool bumpsock (bool failure) = 0; bool udpinit (); bool tcpinit (); void cantsend (); bool resend (bool udp, bool tcp); static void failreq (int err, dnsreq *r) { r->fail (err); } void pktready (bool tcp, u_char *qb, ssize_t size); void udpcheck_cb (ptr h, int err); public: time_t last_resp; // Last time of valid reply from this server time_t last_bump; ref destroyed; ihash reqtab; tmoq reqtoq; resolver (); virtual ~resolver (); bool setsock (bool failure); void sendreq (dnsreq *r); virtual const char *srchlist (int n) { return n <= 0 ? "" : NULL; } u_int16_t genid (); void udpcheck (); }; class resolv_conf : public resolver { protected: parsed_resolv_conf resconf; int ns_idx; time_t last_reload; ifchgcb_t *ifc; ref destroyed; struct stat lastresconf; void reload (bool failure); protected: bool bumpsock (bool failure); public: str resolv_conf_path; resolv_conf (); ~resolv_conf (); const char *srchlist (int n); }; #endif /* _ASYNC_DNSIMPL_H_ */ avenger-0.8.5/libasync/aerr.C0000644000175000017500000000613011221237220012725 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "async.h" #include static suio *erruio = New suio; static void _err_output_async (suio *, int); static void _err_reset_async () { erruio->clear (); fdcb (errfd, selwrite, NULL); } void err_init () { int flags; erruio->clear (); if ((flags = fcntl (errfd, F_GETFL, 0)) != -1) fcntl (errfd, F_SETFL, flags|O_APPEND); _err_output = _err_output_async; _err_reset_hook = _err_reset_async; } void err_flush () { if (_err_output != _err_output_async) return; make_sync (errfd); erruio->output (errfd); } static void err_wcb () { int n; int cnt; if (!erruio->resid () || _err_output != _err_output_async) { fdcb (errfd, selwrite, NULL); return; } /* Try to write whole lines at a time. */ for (cnt = min (erruio->iovcnt (), (size_t) UIO_MAXIOV); cnt > 0 && (erruio->iov ()[cnt-1].iov_len == 0 || *((char *) erruio->iov ()[cnt-1].iov_base + erruio->iov ()[cnt-1].iov_len - 1) != '\n'); cnt--) ; if (!cnt) { if (erruio->iovcnt () < UIO_MAXIOV) { /* Wait for a carriage return */ fdcb (errfd, selwrite, NULL); return; } else cnt = -1; } /* Write asynchronously, but keep stderr synchronous in case of * emergency (e.g. maybe assert wants to fprintf to stderr). */ if (globaldestruction) n = erruio->output (errfd, cnt); else { _make_async (errfd); n = erruio->output (errfd, cnt); make_sync (errfd); } if (n < 0) err_reset (); if (erruio->resid () && !globaldestruction) fdcb (errfd, selwrite, wrap (err_wcb)); else fdcb (errfd, selwrite, NULL); } void _err_output_async (suio *uio, int flags) { int saved_errno = errno; if (flags & warnobj::panicflag) { erruio->copyu (uio); make_sync (errfd); erruio->output (errfd); myabort (); } /* Start new iovecs after newlines so as to output entire lines when * possible. */ if (erruio->resid ()) { const iovec *iovp = erruio->iov () + erruio->iovcnt () - 1; if (((char *) iovp->iov_base)[iovp->iov_len - 1] == '\n') erruio->breakiov (); } erruio->copyu (uio); if (flags & warnobj::fatalflag) { err_flush (); exit (1); } err_wcb (); errno = saved_errno; } EXITFN (exitflush); static void exitflush () { if (_err_output != _err_output_async) { err_flush (); err_reset (); } } avenger-0.8.5/libasync/vatmpl.h0000644000175000017500000001102011221237220013336 00000000000000#if 0 /* -*-perl-*- */ # /* # $Id$ # # This header file was automatically generated by itself. # (Yup, it's a C++ header file and a perl script.) # # Copyright (C) 1998 David Mazieres (dm@uun.org) # # 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 # # Note: For the purposes of the GNU General Public License, source # includes the source to the perl script, not just the resulting # header file, callback.h. However, since the perl script is # conveniently embedded in the header file, you needn't do anything # special to distribute source as long as you don't take the perl out # of the header. eval 'exec perl -w -S $0 ${1+"$@"}' if 0; use strict; use vars qw(@a); my $NA = 10; seek DATA, 0, 0; while () { print; last if m/^\#endif \/\* perl \*\/$/; } print <<'EOF;'; #ifndef _VATMPL_H_INCLUDED_ #define _VATMPL_H_INCLUDED_ 1 EOF; print <<'EOF;'; #define COMMA , #define LPAREN ( #define RPAREN ) EOF; sub jc(@) { join (', ', @_); } sub nlist ($) { my $pat = shift; jc (map { my $ret = $pat; $ret =~ s/%/$_/g; $ret; } @a); } sub pdef(\@) { my $ar = shift; foreach $_ (@$ar[0 .. $#$ar - 1]) { my $nt = int ((71 - length ($_)) / 8); print $_, ($nt > 0 ? "\t" x $nt : ' '), "\\\n"; } print $$ar[$#$ar], "\n" if @$ar; } my @lines; push @lines, '#define VA_TEMPLATE(fn, start, end)'; my $a; for ($a = 0; $a <= $NA; $a++) { local @a = (1 .. $a); push @lines, '', sprintf ("template<%s>", nlist 'class A%') if ($a > 0); push @lines, sprintf ("fn (%s)", nlist 'const A% &a%'); push @lines, sprintf (" start (%s) end", nlist 'a%'); } pdef @lines; print "\n"; @lines = (); print "\n", '#endif /', '* !_VATMPL_H_INCLUDED_ *', '/', "\n"; __END__ # */ #endif /* perl */ #ifndef _VATMPL_H_INCLUDED_ #define _VATMPL_H_INCLUDED_ 1 #define COMMA , #define LPAREN ( #define RPAREN ) #define VA_TEMPLATE(fn, start, end) \ fn () \ start () end \ \ template \ fn (const A1 &a1) \ start (a1) end \ \ template \ fn (const A1 &a1, const A2 &a2) \ start (a1, a2) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3) \ start (a1, a2, a3) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4) \ start (a1, a2, a3, a4) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5) \ start (a1, a2, a3, a4, a5) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6) \ start (a1, a2, a3, a4, a5, a6) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6, const A7 &a7) \ start (a1, a2, a3, a4, a5, a6, a7) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6, const A7 &a7, const A8 &a8) \ start (a1, a2, a3, a4, a5, a6, a7, a8) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6, const A7 &a7, const A8 &a8, const A9 &a9) \ start (a1, a2, a3, a4, a5, a6, a7, a8, a9) end \ \ template \ fn (const A1 &a1, const A2 &a2, const A3 &a3, const A4 &a4, const A5 &a5, const A6 &a6, const A7 &a7, const A8 &a8, const A9 &a9, const A10 &a10) \ start (a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) end #endif /* !_VATMPL_H_INCLUDED_ */ avenger-0.8.5/libasync/async.h0000644000175000017500000000512511221237220013161 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_ASYNC_H_ #define _ASYNC_ASYNC_H_ 1 #include "amisc.h" #include "init.h" /* core.C */ struct timecb_t; struct lazycb_t; extern timespec tsnow; extern const time_t &timenow; INIT (async_init); void amain () __attribute__ ((noreturn)); void acheck (); void chldcb (pid_t, cbi::ptr); cbv::ptr sigcb (int, cbv::ptr, int = 0); void fdcb (int, selop, cbv::ptr); timecb_t *timecb (const timespec &ts, cbv cb); timecb_t *delaycb (time_t sec, u_int32_t nsec, cbv cb); void timecb_remove (timecb_t *); lazycb_t *lazycb (time_t min_interval, cbv cb); void lazycb_remove (lazycb_t *lazy); inline timecb_t * timecb (time_t tm, cbv cb) { timespec ts = { tm, 0 }; return timecb (ts, cb); } inline timecb_t * delaycb (time_t tm, cbv cb) { return delaycb (tm, 0, cb); } /* aerr.C */ void err_init (); void err_flush (); /* tcpconnect.C */ struct srvlist; struct tcpconnect_t; tcpconnect_t *tcpconnect (in_addr addr, u_int16_t port, cbi cb); tcpconnect_t *tcpconnect (str hostname, u_int16_t port, cbi cb, bool dnssearch = true, str *namep = NULL); tcpconnect_t *tcpconnect_srv (str hostname, str service, u_int16_t defport, cbi cb, bool dnssearch = true, ptr *srvlp = NULL, str *np = NULL); tcpconnect_t *tcpconnect_srv_retry (ref srvl, cbi cb, str *np = NULL); void tcpconnect_cancel (tcpconnect_t *tc); /* ident.C */ void identptr (int fd, callback, int>::ref, unsigned timeout = 15); void ident (int fd, callback::ref, unsigned timeout = 15); /* pipe2str.C */ void pipe2str (int fd, cbs cb, int *fdp = NULL, strbuf *sb = NULL); void chldrun (cbi chld, cbs cb); /* ifchg.C */ struct ifchgcb_t; extern vec ifchg_addrs; extern u_int64_t ifchg_count; ifchgcb_t *ifchgcb (cbv); void ifchgcb_remove (ifchgcb_t *chg); #endif /* !_ASYNC_ASYNC_H_ */ avenger-0.8.5/libasync/err.C0000644000175000017500000001230711221237220012567 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "err.h" #undef warn #undef warnx #undef vwarn #undef vwarnx #undef fatal #undef panic bssstr progname; bssstr progpid; str progdir; void (*fatalhook) (); int errfd = 2; bool fatal_no_destruct; void (*_err_output) (suio *uio, int flags) = _err_output_sync; void (*_err_reset_hook) (); #if DMALLOC_VERSION_MAJOR < 5 #define dmalloc_logpath _dmalloc_logpath extern "C" char *dmalloc_logpath; #endif /* DMALLOC_VERSION_MAJOR < 5 */ void setprogname (char *argv0) { char *cp; if ((cp = strrchr (argv0, '/'))) cp++; else cp = argv0; /* Libtool shell wrappers leave lt- in argv[0] */ if (cp[0] == 'l' && cp[1] == 't' && cp[2] == '-') progname = cp + 3; else progname = cp; if (cp > argv0) progdir.setbuf (argv0, cp - argv0); else progdir = NULL; #ifdef DMALLOC if (dmalloc_logpath) { str logname; const char *p; if (!(p = strrchr (dmalloc_logpath, '/')) || !(p = strrchr (p, '.'))) p = dmalloc_logpath + strlen (dmalloc_logpath); logname = strbuf ("%.*s.%s", int (p - dmalloc_logpath), dmalloc_logpath, progname.cstr ()); static char *lp; if (lp) xfree (lp); lp = xstrdup (logname); dmalloc_logpath = lp; } #endif /* DMALLOC */ } void setprogpid (int p) { strbuf b ("%d", p); progpid = b; } void err_reset () { if (_err_reset_hook) (*_err_reset_hook) (); _err_reset_hook = NULL; _err_output = _err_output_sync; } void _err_output_sync (suio *uio, int flags) { int saved_errno = errno; uio->output (errfd); if (flags & warnobj::panicflag) myabort (); if (flags & warnobj::fatalflag) { if (fatalhook) (*fatalhook) (); if (fatal_no_destruct) _exit (1); exit (1); } errno = saved_errno; } static const char * timestring () { timespec ts; clock_gettime (CLOCK_REALTIME, &ts); static str buf; buf = strbuf ("%d.%06d", int (ts.tv_sec), int (ts.tv_nsec/1000)); return buf; } /* * warnobj */ warnobj::warnobj (int f) : flags (f) { if (flags & timeflag) cat (timestring ()).cat (" "); if (!(flags & xflag) && progname) { if (progpid) cat (progname).cat ("[").cat (progpid).cat ("]: "); else cat (progname).cat (": "); } if (flags & panicflag) cat ("PANIC: "); else if (flags & fatalflag) cat ("fatal: "); } const warnobj & warnobj::operator() (const char *fmt, ...) const { va_list ap; va_start (ap, fmt); vfmt (fmt, ap); va_end (ap); return *this; } warnobj::~warnobj () { _err_output (uio, flags); } #ifndef fatalobj fatalobj::~fatalobj () { /* Of course, gcc won't let this function return, so we have to jump * through a few hoops rather than simply implement ~fatalobj as * {}. */ static_cast (this)->~warnobj (); myabort (); } #endif /* !fatalobj */ void traceobj::init () { if (progname) cat (progname).cat (": "); cat (prefix); if (dotime) cat (timestring ()).cat (" "); } traceobj::~traceobj () { if (doprint) _err_output (uio, 0); } const traceobj & traceobj::operator() (const int threshold) { doprint = current_level >= threshold; if (doprint) init (); return *this; } const traceobj & traceobj::operator() (const int threshold, const char *fmt, ...) { doprint = current_level >= threshold; if (doprint) { init (); va_list ap; va_start (ap, fmt); vfmt (fmt, ap); va_end (ap); } return *this; } /* * Traditional functions */ void sfs_vwarn (const char *fmt, va_list ap) { suio uio; if (progname) uio.print (progname.cstr (), progname.len ()); suio_vuprintf (&uio, fmt, ap); _err_output (&uio, 0); } void sfs_vwarnx (const char *fmt, va_list ap) { suio uio; suio_vuprintf (&uio, fmt, ap); _err_output (&uio, warnobj::xflag); } void sfs_warn (const char *fmt, ...) { va_list ap; va_start (ap, fmt); sfs_vwarn (fmt, ap); va_end (ap); } void sfs_warnx (const char *fmt, ...) { va_list ap; va_start (ap, fmt); sfs_vwarnx (fmt, ap); va_end (ap); } void fatal (const char *fmt, ...) { va_list ap; strbuf b; if (progname) b << progname << ": "; b << "fatal: "; va_start (ap, fmt); b.vfmt (fmt, ap); va_end (ap); _err_output (b.tosuio (), warnobj::fatalflag); exit (1); } void panic (const char *fmt, ...) { va_list ap; strbuf b; if (progname) b << progname << ": "; b << "PANIC: " << __BACKTRACE__ << "\n"; va_start (ap, fmt); b.vfmt (fmt, ap); va_end (ap); _err_output (b.tosuio (), warnobj::panicflag); myabort (); } GLOBALDESTRUCT; avenger-0.8.5/libasync/daemonize.C0000644000175000017500000001105211221237220013746 00000000000000/* $Id$ */ /* * * Copyright (C) 1999 David Mazieres (dm@uun.org) * * 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 * */ #include "async.h" str syslog_priority ("daemon.notice"); static int start_log_to_file (const str &line, const str &logfile, int flags, mode_t m) { int fd; int n; if ((fd = open (logfile.cstr (), flags, m)) < 0) { warn ("%s: %m\n", logfile.cstr ()); fd = errfd; } else { warn << "Logging via logfile: " << logfile << "\n"; if (line) { n = write (fd, line.cstr (), line.len ()); if (n < (int (line.len ()))) warn << logfile << ": write to logfile failed\n"; } } return fd; } int start_logger (const str &priority, const str &tag, const str &line, const str &logfile, int flags, mode_t mode) { #ifdef PATH_LOGGER const char *av[] = { PATH_LOGGER, "-p", NULL, "-t", NULL, NULL, NULL }; av[2] = const_cast (priority.cstr ()); if (line) av[5] = const_cast (line.cstr ()); else av[5] = "log started"; if (tag) av[4] = const_cast (tag.cstr ()); else av[4] = ""; pid_t pid; int status; if ((pid = spawn (PATH_LOGGER, av, 0, 0, errfd)) < 0) { warn ("%s: %m\n", PATH_LOGGER); return start_log_to_file (line, logfile, flags, mode); } if (waitpid (pid, &status, 0) <= 0 || !WIFEXITED (status) || WEXITSTATUS (status)) return start_log_to_file (line, logfile, flags, mode); int fds[2]; if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0) fatal ("socketpair: %m\n"); close_on_exec (fds[0]); if (fds[1] != 0) close_on_exec (fds[1]); av[5] = NULL; if (spawn (PATH_LOGGER, av, fds[1], 0, 0) >= 0) { close (fds[1]); return fds[0]; } else warn ("%s: %m\n", PATH_LOGGER); #endif /* PATH_LOGGER */ return start_log_to_file (line, logfile, flags, mode); } void start_logger (str tag) { #ifdef PATH_LOGGER if (!tag) tag = ""; const char *av[] = { PATH_LOGGER, "-p", const_cast (syslog_priority.cstr ()), "-t", const_cast (tag.cstr ()), NULL}; int fds[2]; close (0); if (int fd = open ("/dev/null", O_RDONLY)) close (fd); if (socketpair (AF_UNIX, SOCK_STREAM, 0, fds) < 0) fatal ("socketpair: %m\n"); close_on_exec (fds[0]); if (fds[1] != 0) close_on_exec (fds[1]); if (spawn (PATH_LOGGER, av, fds[1], 0, 0) >= 0) { close (fds[1]); if (fds[0] != errfd) { err_flush (); // XXX - we shouldn't depend on aerr.C if (dup2 (fds[0], errfd) < 0) fatal ("dup2: %m\n"); close (fds[0]); } if (errfd != 1) dup2 (errfd, 1); return; } else warn ("%s: %m\n", PATH_LOGGER); #endif /* PATH_LOGGER */ /* No logger, at least send chatter to stdout rather than stderr, so * that it can be redirected. */ dup2 (errfd, 1); } struct pidfile { const str path; const struct stat sb; pidfile (str p, struct stat s) : path (p), sb (s) {} }; static vec pidfiles; EXITFN(pidclean); static void pidclean () { for (; !pidfiles.empty (); pidfiles.pop_front ()) { pidfile &pf = pidfiles.front (); struct stat sb; if (!stat (pf.path, &sb) && sb.st_dev == pf.sb.st_dev && sb.st_ino == pf.sb.st_ino) unlink (pf.path); } } void daemonize (str tag) { switch (fork ()) { default: _exit (0); case -1: fatal ("fork: %m\n"); case 0: break; } if (setsid () == -1) fatal ("setsid: %m\n"); if (!builddir) { start_logger (tag); str path = strbuf () << PIDDIR << "/" << progname << ".pid"; struct stat sb; if (str2file (path, strbuf ("%d\n", int (getpid ())), 0444, false, &sb)) pidfiles.push_back (pidfile (path, sb)); } else { str piddir = buildtmpdir; if (!piddir) piddir = builddir; str path = strbuf () << piddir << "/" << progname << ".pid"; struct stat sb; if (str2file (path, strbuf ("%d\n", int (getpid ())), 0444, false, &sb)) pidfiles.push_back (pidfile (path, sb)); } } avenger-0.8.5/libasync/suio_vuprintf.C0000644000175000017500000004430711221237220014720 00000000000000/* $Id$ */ /*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #undef FLOATING_POINT #include "suio++.h" #ifdef FLOATING_POINT #include #include /* 11-bit exponent (VAX G floating point) is 308 decimal digits */ #define MAXEXP 308 /* 128 bit fraction takes up 39 decimal digits; max reasonable precision */ #define MAXFRACT 39 #define BUF (MAXEXP+MAXFRACT+1) /* + decimal point */ #define DEFPREC 6 static char *cvt (double, int, int, char *, int *, int, int *); static int exponent (char *, int, int); #else /* ! FLOATING_POINT */ #define BUF 40 #endif /* ! FLOATING_POINT */ /* * Macros for converting digits to letters and vice versa */ #define to_digit(c) ((c) - '0') #define is_digit(c) ((unsigned)to_digit(c) <= 9) #define to_char(n) ((n) + '0') /* * Flags used during conversion. */ #define ALT 0x001 /* alternate form */ #define HEXPREFIX 0x002 /* add 0x or 0X prefix */ #define LADJUST 0x004 /* left adjustment */ #define LONGDBL 0x008 /* long double; unimplemented */ #define LONGINT 0x010 /* long integer */ #define QUADINT 0x020 /* quad integer */ #define SHORTINT 0x040 /* short integer */ #define ZEROPAD 0x080 /* zero (as opposed to blank) pad */ #define FPT 0x100 /* Floating point number */ #define NOCOPY 0x200 /* String contents doesn't have to be copied */ void #ifndef DSPRINTF_DEBUG suio_vuprintf (struct suio *uio, const char *_fmt, va_list ap) #else /* DSPRINTF_DEBUG */ __suio_vuprintf (const char *line, struct suio *uio, const char *_fmt, va_list ap) #endif /* DSPRINTF_DEBUG */ { char *fmt = (char *) _fmt; register int ch; /* character from fmt */ register int n, m; /* handy integers (short term usage) */ register char *cp; /* handy char pointer (short term usage) */ register int flags; /* flags as above */ int width; /* width from format (%8d), or 0 */ int prec; /* precision from format (%.3d), or -1 */ char sign; /* sign prefix (' ', '+', '-', or \0) */ #ifdef FLOATING_POINT char *decimal_point = "."; char softsign; /* temporary negative sign for floats */ double _double = 0.0; /* double precision arguments %[eEfgG] */ int expt; /* integer value of exponent */ int expsize = 0; /* character count for expstr */ int ndig; /* actual number of digits returned by cvt */ char expstr[7]; /* buffer for exponent string */ #endif #define quad_t int64_t #define u_quad_t u_int64_t u_quad_t _uquad; /* integer arguments %[diouxX] */ enum { OCT, DEC, HEX } base; /* base for [diouxX] conversion */ int dprec; /* a copy of prec if [diouxX], 0 otherwise */ int realsz; /* field size expanded by dprec */ int size; /* size of converted field or string */ const char *xdigs = ""; /* digits for [xX] conversion */ char buf[BUF]; /* space for %c, %[diouxX], %[eEfgG] */ char ox[2]; /* space for 0x hex-prefix */ /* * To extend shorts properly, we need both signed and unsigned * argument extraction methods. */ #define SARG() \ (flags&QUADINT ? va_arg(ap, quad_t) : \ flags&LONGINT ? va_arg(ap, long) : \ flags&SHORTINT ? (long)(short)va_arg(ap, int) : \ (long)va_arg(ap, int)) #define UARG() \ (flags&QUADINT ? va_arg(ap, u_quad_t) : \ flags&LONGINT ? va_arg(ap, u_long) : \ flags&SHORTINT ? (u_long)(u_short)va_arg(ap, int) : \ (u_long)va_arg(ap, u_int)) /* * Scan the format for conversions (`%' character). */ for (;;) { cp = fmt; while (*fmt > 0) { if (*fmt == '%') break; fmt++; } if ((m = fmt - cp) != 0) suio_print (uio, cp, m); if (!*fmt) goto done; fmt++; /* skip over '%' */ flags = 0; dprec = 0; width = 0; prec = -1; sign = '\0'; rflag: ch = *fmt++; reswitch: switch (ch) { case ' ': /* * ``If the space and + flags both appear, the space * flag will be ignored.'' * -- ANSI X3J11 */ if (!sign) sign = ' '; goto rflag; case '#': flags |= ALT; goto rflag; case '*': /* * ``A negative field width argument is taken as a * - flag followed by a positive field width.'' * -- ANSI X3J11 * They don't exclude field widths read from args. */ if ((width = va_arg (ap, int)) >= 0) goto rflag; width = -width; /* FALLTHROUGH */ case '-': flags |= LADJUST; goto rflag; case '+': sign = '+'; goto rflag; case '.': if ((ch = *fmt++) == '*') { n = va_arg (ap, int); prec = n < 0 ? -1 : n; goto rflag; } n = 0; while (is_digit (ch)) { n = 10 * n + to_digit (ch); ch = *fmt++; } prec = n < 0 ? -1 : n; goto reswitch; case '0': /* * ``Note that 0 is taken as a flag, not as the * beginning of a field width.'' * -- ANSI X3J11 */ flags |= ZEROPAD; goto rflag; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = 0; do { n = 10 * n + to_digit (ch); ch = *fmt++; } while (is_digit (ch)); width = n; goto reswitch; #ifdef FLOATING_POINT case 'L': flags |= LONGDBL; goto rflag; #endif case 'h': flags |= SHORTINT; goto rflag; case 'l': if (*fmt == 'l') { fmt++; flags |= QUADINT; } else { flags |= LONGINT; } goto rflag; case 'q': flags |= QUADINT; goto rflag; case 'c': *(cp = buf) = va_arg (ap, int); size = 1; sign = '\0'; break; case 'D': flags |= LONGINT; /*FALLTHROUGH */ case 'd': case 'i': _uquad = SARG (); if ((quad_t) _uquad < 0) { _uquad = -_uquad; sign = '-'; } base = DEC; goto number; #ifdef FLOATING_POINT case 'e': case 'E': case 'f': case 'g': case 'G': if (prec == -1) { prec = DEFPREC; } else if ((ch == 'g' || ch == 'G') && prec == 0) { prec = 1; } if (flags & LONGDBL) { _double = (double) va_arg (ap, long double); } else { _double = va_arg (ap, double); } /* do this before tricky precision changes */ if (isinf (_double)) { if (_double < 0) sign = '-'; cp = "Inf"; size = 3; break; } if (isnan (_double)) { cp = "NaN"; size = 3; break; } flags |= FPT; cp = cvt (_double, prec, flags, &softsign, &expt, ch, &ndig); if (ch == 'g' || ch == 'G') { if (expt <= -4 || expt > prec) ch = (ch == 'g') ? 'e' : 'E'; else ch = 'g'; } if (ch <= 'e') { /* 'e' or 'E' fmt */ --expt; expsize = exponent (expstr, expt, ch); size = expsize + ndig; if (ndig > 1 || flags & ALT) ++size; } else if (ch == 'f') { /* f fmt */ if (expt > 0) { size = expt; if (prec || flags & ALT) size += prec + 1; } else /* "0.X" */ size = prec + 2; } else if (expt >= ndig) { /* fixed g fmt */ size = expt; if (flags & ALT) ++size; } else size = ndig + (expt > 0 ? 1 : 2 - expt); if (softsign) sign = '-'; break; #endif /* FLOATING_POINT */ #if 0 /* Disable "%n", as we don't need it--you can always print to a * suio and use suio::resid () to get the buffer size. */ case 'n': if (flags & QUADINT) *va_arg (ap, quad_t *) = uio->resid (); else if (flags & LONGINT) *va_arg (ap, long *) = uio->resid (); else if (flags & SHORTINT) *va_arg (ap, short *) = uio->resid (); else *va_arg (ap, int *) = uio->resid (); continue; /* no output */ #endif case 'O': flags |= LONGINT; /*FALLTHROUGH */ case 'o': _uquad = UARG (); base = OCT; goto nosign; case 'p': /* * ``The argument shall be a pointer to void. The * value of the pointer is converted to a sequence * of printable characters, in an implementation- * defined manner.'' * -- ANSI X3J11 */ /* NOSTRICT */ _uquad = (u_long) va_arg (ap, void *); base = HEX; xdigs = "0123456789abcdef"; flags |= HEXPREFIX; ch = 'x'; goto nosign; case 'm': cp = strerror (errno); goto gotcp; case 's': cp = va_arg (ap, char *); gotcp: if (cp == NULL) panic ("suio_vuprintf: NULL pointer\n"); //cp = "(null)"; if (prec >= 0) { /* * can't use strlen; can only look for the * NUL in the first `prec' characters, and * strlen() will go further. */ char *p = (char *) memchr (cp, 0, prec); if (p != NULL) { size = p - cp; if (size > prec) size = prec; } else size = prec; } else size = strlen (cp); sign = '\0'; if (!(flags & ALT)) flags |= NOCOPY; break; case 'U': flags |= LONGINT; /*FALLTHROUGH */ case 'u': _uquad = UARG (); base = DEC; goto nosign; case 'X': xdigs = "0123456789ABCDEF"; goto hex; case 'x': xdigs = "0123456789abcdef"; hex: _uquad = UARG (); base = HEX; /* leading 0x/X only if non-zero */ if (flags & ALT && _uquad != 0) flags |= HEXPREFIX; /* unsigned conversions */ nosign: sign = '\0'; /* * ``... diouXx conversions ... if a precision is * specified, the 0 flag will be ignored.'' * -- ANSI X3J11 */ number: if ((dprec = prec) >= 0) flags &= ~ZEROPAD; /* * ``The result of converting a zero value with an * explicit precision of zero is no characters.'' * -- ANSI X3J11 */ cp = buf + BUF; if (_uquad != 0 || prec != 0) { /* * Unsigned mod is hard, and unsigned mod * by a constant is easier than that by * a variable; hence this switch. */ switch (base) { case OCT: do { *--cp = to_char (_uquad & 7); _uquad >>= 3; } while (_uquad); /* handle octal leading 0 */ if (flags & ALT && *cp != '0') *--cp = '0'; break; case DEC: /* many numbers are 1 digit */ while (_uquad >= 10) { *--cp = to_char (_uquad % 10); _uquad /= 10; } *--cp = to_char (_uquad); break; case HEX: do { *--cp = xdigs[_uquad & 15]; _uquad >>= 4; } while (_uquad); break; default: cp = const_cast ("bug in vfprintf: bad base"); size = strlen (cp); goto skipsize; } } size = buf + BUF - cp; skipsize: break; default: /* "%?" prints ?, unless ? is NUL */ if (ch == '\0') goto done; /* pretend it was %c with argument ch */ cp = buf; *cp = ch; size = 1; sign = '\0'; break; } /* * All reasonable formats wind up here. At this point, `cp' * points to a string which (if not flags&LADJUST) should be * padded out to `width' places. If flags&ZEROPAD, it should * first be prefixed by any sign or other prefix; otherwise, * it should be blank padded before the prefix is emitted. * After any left-hand padding and prefixing, emit zeroes * required by a decimal [diouxX] precision, then print the * string proper, then emit zeroes required by any leftover * floating precision; finally, if LADJUST, pad with blanks. * * Compute actual size, so we know how much to pad. * size excludes decimal prec; realsz includes it. */ realsz = dprec > size ? dprec : size; if (sign) realsz++; else if (flags & HEXPREFIX) realsz += 2; /* right-adjusting blank padding */ if ((flags & (LADJUST | ZEROPAD)) == 0) suio_fill (uio, ' ', width - realsz); /* prefix */ if (sign) { suio_copy (uio, &sign, 1); } else if (flags & HEXPREFIX) { ox[0] = '0'; ox[1] = ch; suio_copy (uio, ox, 2); } /* right-adjusting zero padding */ if ((flags & (LADJUST | ZEROPAD)) == ZEROPAD) suio_fill (uio, '0', width - realsz); /* leading zeroes from decimal precision */ suio_fill (uio, '0', dprec - size); /* the string or number proper */ #ifdef FLOATING_POINT if ((flags & FPT) == 0) { if (flags & NOCOPY) __suio_printcheck (line, uio, cp, size); else suio_copy (uio, cp, size); } else { /* glue together f_p fragments */ if (ch >= 'f') { /* 'f' or 'g' */ if (_double == 0) { /* kludge for __dtoa irregularity */ suio_print (uio, "0", 1); if (expt < ndig || (flags & ALT) != 0) { suio_print (uio, decimal_point, 1); suio_fill (uio, '0', ndig - 1); } } else if (expt <= 0) { suio_print (uio, "0", 1); suio_print (uio, decimal_point, 1); suio_fill (uio, '0', -expt); suio_copy (uio, cp, ndig); } else if (expt >= ndig) { suio_copy (uio, cp, ndig); suio_fill (uio, '0', expt - ndig); if (flags & ALT) suio_print (uio, ".", 1); } else { suio_copy (uio, cp, expt); cp += expt; suio_print (uio, ".", 1); suio_copy (uio, cp, ndig - expt); } } else { /* 'e' or 'E' */ if (ndig > 1 || flags & ALT) { ox[0] = *cp++; ox[1] = '.'; suio_copy (uio, ox, 2); if (_double || (flags & ALT) == 0) { suio_copy (uio, cp, ndig - 1); } else /* 0.[0..] */ /* __dtoa irregularity */ suio_fill (uio, '0', ndig - 1); } else /* XeYYY */ suio_copy (uio, cp, 1); suio_copy (uio, expstr, expsize); } } #else if (flags & NOCOPY) #ifndef DSPRINTF_DEBUG suio_print (uio, cp, size); #else /* DSPRINTF_DEBUG */ __suio_printcheck (line, uio, cp, size); #endif /* DSPRINTF_DEBUG */ else suio_copy (uio, cp, size); #endif /* left-adjusting padding (always blank) */ if (flags & LADJUST) suio_fill (uio, ' ', width - realsz); } done: return; } #ifdef FLOATING_POINT extern char *__dtoa (double, int, int, int *, int *, char **); static char * cvt (value, ndigits, flags, sign, decpt, ch, length) double value; int ndigits, flags, *decpt, ch, *length; char *sign; { int mode, dsgn; char *digits, *bp, *rve; if (ch == 'f') { mode = 3; /* ndigits after the decimal point */ } else { /* To obtain ndigits after the decimal point for the 'e' * and 'E' formats, round to ndigits + 1 significant * figures. */ if (ch == 'e' || ch == 'E') { ndigits++; } mode = 2; /* ndigits significant digits */ } if (value < 0) { value = -value; *sign = '-'; } else *sign = '\000'; digits = __dtoa (value, mode, ndigits, decpt, &dsgn, &rve); if ((ch != 'g' && ch != 'G') || flags & ALT) { /* Print trailing zeros */ bp = digits + ndigits; if (ch == 'f') { if (*digits == '0' && value) *decpt = -ndigits + 1; bp += *decpt; } if (value == 0) /* kludge for __dtoa irregularity */ rve = bp; while (rve < bp) *rve++ = '0'; } *length = rve - digits; return (digits); } static int exponent (p0, exp, fmtch) char *p0; int exp, fmtch; { register char *p, *t; char expbuf[MAXEXP]; p = p0; *p++ = fmtch; if (exp < 0) { exp = -exp; *p++ = '-'; } else *p++ = '+'; t = expbuf + MAXEXP; if (exp > 9) { do { *--t = to_char (exp % 10); } while ((exp /= 10) > 9); *--t = to_char (exp); for (; t < expbuf + MAXEXP; *p++ = *t++); } else { *p++ = '0'; *p++ = to_char (exp); } return (p - p0); } #endif /* FLOATING_POINT */ void #ifndef DSPRINTF_DEBUG suio_uprintf (struct suio *uio, const char *fmt, ...) #else /* DSPRINTF_DEBUG */ __suio_uprintf (const char *line, struct suio *uio, const char *fmt, ...) #endif /* DSPRINTF_DEBUG */ { va_list ap; va_start (ap, fmt); #ifndef DSPRINTF_DEBUG suio_vuprintf (uio, fmt, ap); #else /* DSPRINTF_DEBUG */ __suio_vuprintf (line, uio, fmt, ap); #endif /* DSPRINTF_DEBUG */ va_end (ap); } avenger-0.8.5/libasync/fdlim.h0000644000175000017500000000471611221237220013144 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 FDLIM_H #define FDLIM_H #include #include #include #include #define FDLIM_MAX 0x10000 static int fdlim_get (int hard) { #ifdef RLIMIT_NOFILE struct rlimit rlfd; if (getrlimit (RLIMIT_NOFILE, &rlfd) < 0) return -1; #ifdef RLIM_INFINITY /* not defined on HPSUX */ if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY) return FDLIM_MAX; else #endif /* RLIM_INFINITY */ return hard ? rlfd.rlim_max : rlfd.rlim_cur; #else /* !RLIMIT_NOFILE */ #ifdef HAVE_GETDTABLESIZE return getdtablesize (); #else /* !HAVE_GETDTABLESIZE */ #ifdef _SC_OPEN_MAX return (sysconf (_SC_OPEN_MAX)); #else /* !_SC_OPEN_MAX */ #ifdef NOFILE return (NOFILE); #else /* !NOFILE */ return 25; #endif /* !NOFILE */ #endif /* !_SC_OPEN_MAX */ #endif /* !HAVE_GETDTABLESIZE */ #endif /* !RLIMIT_NOFILE */ } static int fdlim_set (rlim_t lim, int hard) { #ifdef RLIMIT_NOFILE struct rlimit rlfd; if (lim <= 0) return -1; if (getrlimit (RLIMIT_NOFILE, &rlfd) < 0) return -1; #ifdef RLIMIT_INFINITY if (lim >= FDLIM_MAX) lim = RLIM_INFINITY; #endif /* RLIMIT_INFINITY */ switch (hard) { case 0: rlfd.rlim_cur = (lim <= rlfd.rlim_max) ? lim : rlfd.rlim_max; break; case 1: rlfd.rlim_cur = lim; if (lim > rlfd.rlim_max) rlfd.rlim_max = lim; break; case -1: rlfd.rlim_max = lim; if (rlfd.rlim_cur > lim) rlfd.rlim_cur = lim; break; default: #ifdef assert assert (0); #else /* !assert */ return -1; #endif /* !assert */ } if (setrlimit (RLIMIT_NOFILE, &rlfd) < 0) return -1; return 0; #else /* !RLIMIT_NOFILE */ return -1; #endif /* !RLIMIT_NOFILE */ } #endif /* FDLIM_H */ avenger-0.8.5/libasync/qhash.h0000644000175000000120000001265212077217760013162 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _QHASH_H_ #define _QHASH_H_ 1 #include "ihash.h" template struct qhash_lookup_return { typedef T *type; typedef const T *const_type; static type ret (T *v) { return v; } static const_type const_ret (T *v) { return v; } }; template struct qhash_lookup_return > { typedef ptr type; typedef ptr const_type; static type ret (ref *v) { if (v) return *v; return NULL; } static const_type const_ret (ref *v) { if (v) return *v; return NULL; } }; template struct qhash_lookup_return { typedef T *type; typedef const T *const_type; static type ret (T *v) { return v; } static const_type const_ret (T *v) { return v; } }; template struct qhash_slot { ihash_entry link; const K key; V value; qhash_slot (const K &k, typename CREF (V) v) : key (k), value (v) {} qhash_slot (const K &k, typename NCREF (V) v) : key (k), value (v) {} }; template, class E = equals, // XXX - We need to kludge this for both g++ and KCC class R = qhash_lookup_return, ihash_entry > qhash_slot::*kludge = &qhash_slot::link> class qhash : public ihash_core, kludge> { public: typedef qhash_slot slot; typedef ihash_core core; private: const E eq; const H hash; slot *getslot (const K &k) const { slot *s; for (s = this->lookup_val (hash (k)); s && !eq (s->key, k); s = this->next_val (s)) ; return s; } void delslot (slot *s) { core::remove (s); delete s; } static void mkcb (ref > cb, slot *s) { (*cb) (s->key, R::ret (&s->value)); } static void mkcbr (ref > cb, slot *s) { (*cb) (s->key, R::ret (&s->value)); } public: qhash () : eq (E ()), hash (H ()) {} void clear () { core::traverse (wrap (this, &qhash::delslot)); core::clear (); } ~qhash () { clear (); } #if 0 void traverse (callback::ref cb) { core::traverse (wrap (mkcb, cb)); } #endif void traverse (ref > cb) { core::traverse (wrap (mkcbr, cb)); } void insert (const K &k) { if (slot *s = getslot (k)) s->value = V (); else core::insert_val (New slot (k, V ()), hash (k)); } void insert (const K &k, typename CREF (V) v) { if (slot *s = getslot (k)) s->value = v; else core::insert_val (New slot (k, v), hash (k)); } void insert (const K &k, typename NCREF (V) v) { if (slot *s = getslot (k)) s->value = v; else core::insert_val (New slot (k, v), hash (k)); } void remove (const K &k) { if (slot *s = getslot (k)) delslot (s); } typename R::type operator[] (const K &k) { if (slot *s = getslot (k)) return R::ret (&s->value); else return R::ret (NULL); } typename R::const_type operator[] (const K &k) const { if (slot *s = getslot (k)) return R::const_ret (&s->value); else return R::const_ret (NULL); } }; template struct qhash_slot { ihash_entry link; const K key; qhash_slot (const K &k) : key (k) {} }; template, class E = equals, // XXX - We need to kludge this for both g++ and KCC ihash_entry > qhash_slot::*kludge = &qhash_slot::link> class bhash // : public ihash_core, kludge> { public: typedef qhash_slot slot; typedef ihash_core core; private: const E eq; const H hash; slot *getslot (const K &k) const { slot *s; for (s = this->lookup_val (hash (k)); s && !eq (s->key, k); s = this->next_val (s)) ; return s; } void delslot (slot *s) { core::remove (s); delete s; } static void mkcb (ref > cb, qhash_slot *s) { (*cb) (s->key); } static void mkcbr (ref > cb, qhash_slot *s) { (*cb) (s->key); } public: bhash () {} void clear () { this->deleteall (); } ~bhash () { clear (); } bool insert (const K &k) { if (!getslot (k)) { core::insert_val (New slot (k), hash (k)); return true; } return false; } void remove (const K &k) { if (slot *s = getslot (k)) delslot (s); } bool operator[] (const K &k) const { return getslot (k); } #if 0 void traverse (callback ::ref cb) { core::traverse (wrap (mkcb, cb)); } #endif void traverse (ref > cb) { core::traverse (wrap (mkcbr, cb)); } }; #endif /* !_QHASH_H_ */ avenger-0.8.5/libasync/spawn.C0000644000175000017500000001310011332761414013131 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "amisc.h" #include "rxx.h" #include str execdir (EXECDIR); #ifdef MAINTAINER str builddir; str buildtmpdir; #endif /* MAINTAINER */ static void nop (int) { } #ifdef MAINTAINER bool afork_debug = safegetenv ("AFORK_DEBUG"); #endif /* MAINTAINER */ pid_t afork () { if (pid_t pid = fork ()) return pid; fatal_no_destruct = true; err_reset (); /* If we close/dup2 stderr before an exec, but the exec fails, we * still want warn/fatal to work so as to report the error. */ if (errfd == 2) { int fd = dup (errfd); if (fd < 3) close (fd); else { close_on_exec (fd); errfd = fd; } } /* If we exec, we want the child to get SIGPIPEs again. The signal * mask and SIG_IGN signals are preserved by execve, but not * handlers for specific functions. Thus we change the handler from * the probably more efficient SIG_IGN to an empty function. */ struct sigaction sa; bzero (&sa, sizeof (sa)); sa.sa_handler = nop; sigaction (SIGPIPE, &sa, NULL); #ifdef MAINTAINER if (afork_debug) { warn ("AFORK_DEBUG: child process pid %d\n", getpid ()); sleep (7); } #endif /* MAINTAINER */ return 0; } inline bool execok (const char *path) { struct stat sb; return !stat (path, &sb) && S_ISREG (sb.st_mode) && (sb.st_mode & 0111); } #ifdef MAINTAINER static str searchdir (str dir, str prog) { DIR *dirp = opendir (dir); if (!dirp) return NULL; while (dirent *dp = readdir (dirp)) { struct stat sb; str file = dir << "/" << dp->d_name; str np; if (!stat (file, &sb) && S_ISDIR (sb.st_mode) && execok (np = file << prog)) { closedir (dirp); return np; } } closedir (dirp); return NULL; } #endif /* MAINTAINER */ str fix_exec_path (str path, str dir) { const char *prog = strrchr (path, '/'); if (prog) return path; if (!dir) dir = execdir; path = dir << "/" << path; prog = strrchr (path, '/'); if (!prog) panic ("No EXECDIR for unqualified path %s.\n", path.cstr ()); #ifdef MAINTAINER if (builddir && dir == execdir) { str np; np = builddir << prog; if (execok (np)) return np; np = builddir << prog << prog; if (execok (np)) return np; if (np = searchdir (builddir, prog)) return np; if (np = searchdir (builddir << "/lib", prog)) return np; } #endif /* MAINTAINER */ return path; } str find_program (const char *program) { static rxx colonplus (":+"); str r; if (strchr (program, '/')) { r = program; if (execok (r)) return r; return NULL; } #ifdef MAINTAINER if (builddir) { r = fix_exec_path (program); if (execok (r)) return r; } #endif /* MAINTAINER */ if (progdir) { r = progdir << program; if (execok (r)) return r; } const char *p = getenv ("PATH"); if (!p) return NULL; vec vs; split (&vs, colonplus, p); for (str *sp = vs.base (); sp < vs.lim (); sp++) { if (!*sp || !sp->len ()) continue; r = *sp << "/" << program; if (execok (r)) return r; } return NULL; } str find_program_plus_libsfs (const char *program) { str s = fix_exec_path (program); if (!s || !execok (s)) s = find_program (program); return s; } void setstdfds (int in, int out, int err) { if (in != 0) { dup2 (in, 0); if (in > 2 && in != out && in != err) close (in); } if (out != 1) { dup2 (out, 1); if (out > 2 && out != err) close (out); } if (err != 2) { dup2 (err, 2); if (err > 2) close (err); } } extern bool amain_panic; pid_t spawn (const char *path, char *const *argv, int in, int out, int err, cbv::ptr postforkcb, char *const *env) { int fds[2]; if (pipe (fds) < 0) return -1; close_on_exec (fds[0]); close_on_exec (fds[1]); pid_t pid = afork (); if (pid < 0) return pid; if (!pid) { amain_panic = true; close (fds[0]); setstdfds (in, out, err); if (postforkcb) (*postforkcb) (); if (env) execve (path, argv, env); else execv (path, argv); int saved_err = errno; use (write (fds[1], &saved_err, sizeof (saved_err))); close (fds[1]); // Since we return a useful errno, there is no need to print // anything in the child process. Just exit. _exit (1); } close (fds[1]); int chld_err; int n = read (fds[0], &chld_err, sizeof (chld_err)); close (fds[0]); if (n == 0) return pid; errno = chld_err; return -1; } pid_t aspawn (const char *path, char *const *argv, int in, int out, int err, cbv::ptr postforkcb, char *const *env) { pid_t pid = afork (); if (pid < 0) return pid; if (pid) return pid; setstdfds (in, out, err); if (postforkcb) (*postforkcb) (); if (env) execve (path, argv, env); else execv (path, argv); warn ("%s: %m\n", path); _exit (1); } avenger-0.8.5/libasync/maketables.c0000644000175000017500000001071313357041063014160 00000000000000/************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by: Philip Hazel Copyright (c) 1997-2003 University of Cambridge ----------------------------------------------------------------------------- Permission is granted to anyone to use this software for any purpose on any computer system, and to redistribute it freely, subject to the following restrictions: 1. This software 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. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. 4. If PCRE is embedded in any software that is released under the GNU General Purpose Licence (GPL), then the terms of that licence shall supersede any condition above with which it is incompatible. ----------------------------------------------------------------------------- See the file Tech.Notes for some information on the internals. */ /* This file is compiled on its own as part of the PCRE library. However, it is also included in the compilation of dftables.c, in which case the macro DFTABLES is defined. */ #ifndef DFTABLES #include "internal.h" #endif /************************************************* * Create PCRE character tables * *************************************************/ /* This function builds a set of character tables for use by PCRE and returns a pointer to them. They are build using the ctype functions, and consequently their contents will depend upon the current locale setting. When compiled as part of the library, the store is obtained via pcre_malloc(), but when compiled inside dftables, use malloc(). Arguments: none Returns: pointer to the contiguous block of data */ const unsigned char * pcre_maketables(void) { unsigned char *yield, *p; int i; #ifndef DFTABLES yield = (unsigned char*)(pcre_malloc)(tables_length); #else yield = (unsigned char*)malloc(tables_length); #endif if (yield == NULL) return NULL; p = yield; /* First comes the lower casing table */ for (i = 0; i < 256; i++) *p++ = tolower(i); /* Next the case-flipping table */ for (i = 0; i < 256; i++) *p++ = islower(i)? toupper(i) : tolower(i); /* Then the character class tables. Don't try to be clever and save effort on exclusive ones - in some locales things may be different. Note that the table for "space" includes everything "isspace" gives, including VT in the default locale. This makes it work for the POSIX class [:space:]. */ memset(p, 0, cbit_length); for (i = 0; i < 256; i++) { if (isdigit(i)) { p[cbit_digit + i/8] |= 1 << (i&7); p[cbit_word + i/8] |= 1 << (i&7); } if (isupper(i)) { p[cbit_upper + i/8] |= 1 << (i&7); p[cbit_word + i/8] |= 1 << (i&7); } if (islower(i)) { p[cbit_lower + i/8] |= 1 << (i&7); p[cbit_word + i/8] |= 1 << (i&7); } if (i == '_') p[cbit_word + i/8] |= 1 << (i&7); if (isspace(i)) p[cbit_space + i/8] |= 1 << (i&7); if (isxdigit(i))p[cbit_xdigit + i/8] |= 1 << (i&7); if (isgraph(i)) p[cbit_graph + i/8] |= 1 << (i&7); if (isprint(i)) p[cbit_print + i/8] |= 1 << (i&7); if (ispunct(i)) p[cbit_punct + i/8] |= 1 << (i&7); if (iscntrl(i)) p[cbit_cntrl + i/8] |= 1 << (i&7); } p += cbit_length; /* Finally, the character type table. In this, we exclude VT from the white space chars, because Perl doesn't recognize it as such for \s and for comments within regexes. */ for (i = 0; i < 256; i++) { int x = 0; if (i != 0x0b && isspace(i)) x += ctype_space; if (isalpha(i)) x += ctype_letter; if (isdigit(i)) x += ctype_digit; if (isxdigit(i)) x += ctype_xdigit; if (isalnum(i) || i == '_') x += ctype_word; /* Note: strchr includes the terminating zero in the characters it considers. In this instance, that is ok because we want binary zero to be flagged as a meta-character, which in this sense is any character that terminates a run of data characters. */ if (strchr("*+?{^.$|()[", i) != 0) x += ctype_meta; *p++ = x; } return yield; } /* End of maketables.c */ avenger-0.8.5/libasync/suidprotect.c0000644000175000017500000000607411221237220014410 00000000000000/* $Id$ */ /* * * Copyright (C) 2001 David Mazieres (dm@uun.org) * * 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 * */ #include "sysconf.h" int suidsafe (void) { static int safe; if (!safe) { if (suidprotect && getuid () #if defined (HAVE_ISSETUGID) && issetugid () #elif defined (HAVE_GETEUID) && defined (HAVE_GETEGID) && (getuid () != geteuid () || getgid () != getegid ()) #endif /* HAVE_GETEUID and HAVE_GETEGID */ ) safe = -1; else safe = 1; } return safe < 0 ? 0 : 1; } int execsafe (void) { return (suidprotect || execprotect) ? 0 : 1; } char * safegetenv (const char *name) { return suidsafe () ? getenv (name) : NULL; } extern char **environ; #ifndef PUTENV_COPIES_ARGUMENT #if defined (__sun__) && defined (__svr4__) # define BAD_PUTENV 1 #endif /* __sun__ && __svr4__ */ #if BAD_PUTENV static char **newenvp; static char **badenvp; #endif /* BAD_PUTENV */ int xputenv (const char *s) { char *ss; int ret; #if BAD_PUTENV /* Solaris appears to have a very broken putenv implementation that * calls realloc on memory not allocated by malloc. The effects are * particularly bad when C++ global constructors call putenv before * that start of main. (Perhaps some gcc initialization code fixes * the problem before main is invoked?) Just to be safe, we make * sure environ really points to malloced memory. */ if (!newenvp) { int n; for (n = 0; environ[n]; n++) ; newenvp = malloc ((n + 2) * sizeof (*newenvp)); if (!newenvp) return -1; memcpy (newenvp, environ, (n + 1) * sizeof (environ)); badenvp = environ; } /* Somehow, Solaris stubbornly resets environ to point to crap * memory, so we need to keep resetting it. */ if (environ == badenvp) environ = newenvp; #endif /* BAD_PUTENV */ /* Note: Don't use xstrdup, because we don't always link this file * against libasync. (suidconnect uses it, too) */ ss = strdup (s); if (!ss) return -1; ret = putenv (ss); if (ret < 0) xfree (ss); #if BAD_PUTENV else newenvp = environ; #endif /* BAD_PUTENV */ return ret; } #endif /* !PUTENV_COPIES_ARGUMENT */ #ifndef HAVE_UNSETENV void unsetenv (const char *name) { int len = strlen (name); char **ep; for (ep = environ;; ep++) { if (!*ep) return; else if (!strncmp (name, *ep, len) && (*ep)[len] == '=') break; } while ((ep[0] = ep[1])) ep++; } #endif /* !HAVE_UNSETENV */ avenger-0.8.5/libasync/opnew.h0000644000175000017500000000452311221237220013175 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _NEW_H_INCLUDED_ #define _NEW_H_INCLUDED_ 1 #include #include "sysconf.h" using std::nothrow; #ifdef DMALLOC using std::nothrow_t; static class dmalloc_init { static bool initialized; static void init (); public: bool ok () { return initialized; } dmalloc_init () { if (!initialized) init (); } } __dmalloc_init_obj; struct dmalloc_t {}; extern struct dmalloc_t dmalloc; void *operator new (size_t, dmalloc_t, const char *, int); void *operator new[] (size_t, dmalloc_t, const char *, int); void *operator new (size_t, nothrow_t, const char *, int) throw (); void *operator new[] (size_t, nothrow_t, const char *, int) throw (); #define ntNew new (nothrow, __FILE__, __LINE__) #define New new (dmalloc, __FILE__, __LINE__) #define opnew(size) operator new (size, dmalloc, __FILE__, __LINE__) #if __GNUC__ >= 2 #define DSPRINTF_DEBUG 1 extern int nodelete_ignore_count; struct nodelete_ignore { nodelete_ignore () { nodelete_ignore_count++; } ~nodelete_ignore () { nodelete_ignore_count--; } operator bool () const { return true; } }; void nodelete_addptr (const void *obj, const char *fl, int *fp); void nodelete_remptr (const void *obj, const char *fl, int *fp); #endif /* GCC2 */ #else /* !DMALLOC */ #define ntNew new (nothrow) #define New new #define opnew(size) operator new(size) #endif /* !DMALLOC */ #define vNew (void) New template inline T destroy_return (T &t) { T ret = t; t.~T (); return ret; } // XXX - work around egcs 1.1.2 bug: template inline T * destroy_return (T *&tp) { return tp; } #endif /* !_NEW_H_INCLUDED_ */ avenger-0.8.5/libasync/msb.C0000644000175000017500000000470711221237220012565 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "msb.h" /* Highest bit set in a byte */ const char bytemsb[0x100] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; /* Least set bit (ffs) */ const char bytelsb[0x100] = { 0, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 7, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 8, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 7, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 6, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, }; avenger-0.8.5/libasync/refcnt.h0000644000175000017500000004253311221237220013331 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ /* This is a simple reference counted garbage collector. The usage is * as follows: * * class foo : public bar { ... }; * * ... * ref f = new refcounted ( ... ); * ptr b = f; * f = new refcounted ( ... ); * b = NULL; * * A refcounted takes the same constructor arguments as foo, * except that constructors with more than 7 arguments cannot be * called. (This is because there are no varargs templates. You can * raise the limit from 7 to an arbitrary number if you wish, however, * by editting vatmpl.h.) * * A ptr behaves like a foo *, except that it is reference * counted. The foo will be deleted when all pointers go away. Also, * array subscripts will not work on a ptr. You can only * allocate one reference counted object at a time. * * A ref is like a ptr, except that a ref can never be * NULL. If you try to assign a NULL ptr to a ref you will * get an immediate core dump. The statement "ref = NULL" will * generate a compile time error. * * A "const ref" cannot change what it is pointing to, but the * foo pointed to can be modified. A "ref " points to a * foo you cannot change. A ref can be converted to a ref. In general, you can implicitly convert a ref to a ref * if you can implicitly convert an A* to a B*. * * You can also implicitly convert a ref or ptr to a foo *. * Many functions can get away with taking a foo * instead of a * ptr if they don't eliminate any existing references (or the * foo's address around after returning). * * On both the Pentium and Pentium Pro, a function taking a ref * argument usually seems to take 10-15 more cycles the same function * with a foo * argument. With some versions of g++, though, this * number can go as high as 50 cycles unless you compile with * '-fno-exceptions'. * * Sometimes you want to do something other than simply free an object * when its reference count goes to 0. This can usually be * accomplished by the reference counted object's destructor. * However, after a destructor is run, the memory associated with an * object is freed. If you don't want the object to be deleted, you * can define a finalize method that gets invoked once the reference * count goes to 0. Any class with a finalize method must declare a * virtual base class of refcount. For example: * * class foo : public virtual refcount { * ... * void finalize () { recycle (this); } * }; * * Occasionally you may want to generate a reference counted ref or * ptr from an ordinary pointer. This might, for instance, be used by * the recycle function above. * * You can do this with the function mkref, but again only if the * underlying type has a virtual base class of refcount. Given the * above definition, recycle might do this: * * void * recycle (foo *fp) * { * ref = mkref (fp); * ... * } * * Note that unlike in Java, an objects finalize method will be called * every time the reference count reaches 0, not just the first time. * Thus, there is nothing morally wrong with "resurrecting" objects as * they are being garbage collected. * * Use of mkref is potentially dangerous, however. You can disallow * its use on a per-class basis by simply not giving your object a * public virtual base class of refcount. * * class foo { * // fine, no mkref or finalize allowed * }; * * class foo : private virtual refcount { * void finalize () { ... } * // finalize will work, but not mkref * }; * * If you like to live dangerously, there are a few more things you * can do (but probably shouldn't). You can keep the original * "refcounted *" around and use it to generate more references * from a finalize method (or elsewhere). If foo has a virtual base * class of refcount, it will also inherit the methods refcount_inc() * and refcount_dec(). You can use these to create memory leaks and * crash your program, respectively. * * A note on virtual base classes: refcounted is derived from * type foo. Thus, if foo has any virtual base classes, only the * default constructor will be called when a refcounted is * allocated--regardless of whatever constructor foo's constructor * invokes. As an alternative, you can allocate a * * refcounted * * However, you can only do this if foo does not have a virtual base * class of recounted and foo does not have a finalize class. */ #ifndef _REFCNT_H_INCLUDED_ #define _REFCNT_H_INCLUDED_ 1 #if VERBOSE_REFCNT #include void refcnt_warn (const char *op, const type_info &type, void *addr, int cnt); #endif /* VERBOSE_REFCNT */ #include "opnew.h" #include "vatmpl.h" class __globaldestruction_t { static bool started; public: ~__globaldestruction_t () { started = true; } operator bool () { return started; } }; static __globaldestruction_t globaldestruction; /* The following is for the end of files that use bssptr's */ #define GLOBALDESTRUCT static __globaldestruction_t __gd__ ## __LINE__ template class ref; template class ptr; enum reftype { scalar, vsize, vbase }; template class refcounted; template ref mkref (T *); class refcount { u_int refcount_cnt; virtual void refcount_call_finalize () = 0; friend class refpriv; protected: refcount () : refcount_cnt (0) {} virtual ~refcount () {} void finalize () { delete this; } void refcount_inc () { #if VERBOSE_REFCNT refcnt_warn ("INC", typeid (*this), this, refcount_cnt + 1); #endif /* VERBOSE_REFCNT */ refcount_cnt++; } void refcount_dec () { #if VERBOSE_REFCNT refcnt_warn ("DEC", typeid (*this), this, refcount_cnt - 1); #endif /* VERBOSE_REFCNT */ if (!--refcount_cnt) refcount_call_finalize (); } u_int refcount_getcnt () { return refcount_cnt; } }; class refpriv { protected: /* We introduce a private type "privtype," that users won't have * floating around. The idea is that NULL can implicitly be * converted to a privtype *. Thus, when passing NULL as an * argument to a function taking a ptr, a null ptr will be * constructed. Likewise, if f is of type ptr, the assignment f * = NULL will make f null. By omitting this from ref, we can * ensure that ref f = NULL results in a compile-time error. */ class privtype {}; private: #ifndef NO_TEMPLATE_FRIENDS template friend class ref; template friend class ptr; #else /* NO_TEMPLATE_FRIENDS */ protected: #endif /* NO_TEMPLATE_FRIENDS */ static void rdec (refcount *c) { c->refcount_dec (); } static void rinc (refcount *c) { c->refcount_inc (); } template static void rinc (const ::ref &r) { r.inc (); } template static void rinc (const ::ptr &r) { r.inc (); } template static void rinc (refcounted *pp) { pp->refcount_inc (); } template static T *rp (const ::ref &r) { return r.p; } template static T *rp (const ::ptr &r) { return r.p; } template static T *rp (refcounted *pp) { return *pp; } static refcount *rc (refcount *c) { return c; } // Make gcc happy ??? template static refcount *rc (const ::ref &r) { return r.c; } template static refcount *rc (const ::ptr &r) { return r.c; } template static refcount *rc (refcounted *pp) { return pp; } refcount *c; explicit refpriv (refcount *cc) : c (cc) {} refpriv () {} public: #if 0 template bool operator== (const ::ref &r) const { return c == r.c; } template bool operator== (const ::ptr &r) const { return c == r.c; } template bool operator!= (const ::ref &r) const { return c != r.c; } template bool operator!= (const ::ptr &r) const { return c != r.c; } #else bool operator== (const refpriv &r) const { return c == r.c; } bool operator!= (const refpriv &r) const { return c != r.c; } #endif void *Xleak () const { rinc (c); return c; } static void Xplug (void *c) { rdec ((refcount *) c); } }; template struct type2struct { typedef T type; }; #define TYPE2STRUCT(t, T) \ template struct type2struct { \ struct type { \ T v; \ operator T &() { return v; } \ operator const T &() const { return v; } \ type () {} \ type (const T &vv) : v (vv) {} \ }; \ } TYPE2STRUCT(, bool); TYPE2STRUCT(, char); TYPE2STRUCT(, signed char); TYPE2STRUCT(, unsigned char); TYPE2STRUCT(, int); TYPE2STRUCT(, unsigned int); TYPE2STRUCT(, long); TYPE2STRUCT(, unsigned long); TYPE2STRUCT(class U, U *); template class refcounted : virtual private refcount, private type2struct::type { friend class refpriv; virtual void XXX_gcc_repo_workaround () {} // XXX - egcs bug operator T *() { return &static_cast (*this); } /* When the reference count on an object goes to 0, the object is * deleted by default. However, some classes may not wish to * deallocate their memory at the time the reference count goes to * 0. (For example, a network stream class may wish to finish * writing buffered data to the network asynchronously, and delete * itself at a later point.) * * Classes can therefore specify a (non-virtual) "void finalize ()" * method to be called when the reference count goes to 0. Any * class with a finalize method must also have refcount as a virtual * base class. * * So what is refcount_call_finalize all about? Here is a more * obvious implementation: * * class refcount { * virtual void finalize () { delete this; } * virtual ~refcount () {} * ... * void refcount_dec () { if (!--refcount_cnt) finalize (); } * }; * * class myclass : public virtual refcount { * void finalize () { ... } * }; * * But there are inconveniences. If the user forgets to give * myclass a virtual refcount supertype, the code will still * compile--it will just behave incorrectly at run time. * * This code solves the problem by calling finalize from * refcounted rather than refcount. If the user forgets to give * myclass a virtual refcount subtype, the call to finalize from * refount_call_finalize is ambiguous and flags an error. * * An added benefit of this scheme is that refcount is now a pure * virtual class (call_finalize is an abstract method). This means * myclass also becomes a pure virtual class, and cannot be * allocated on its own (only as part of a refcounted). Of * course, if you really want to circumvent this restriction, you * can do so by giving myclass a virtual call_finalize() method. * The common case will probably be that a class with a finalize * method always expects to be refcounted. This scheme makes it * hard to violate the requirement accidentally. */ void refcount_call_finalize () { /* An error on the following line probably means you forgot to * give T a virtual base class of refcount. Alternatively, T * already has a method called finalize unrelated to the reference * counting. In that case you will have to rename finalize to use * a refcounted. */ finalize (); } ~refcounted () {} public: VA_TEMPLATE (explicit refcounted, : type2struct::type, {}) }; template class refcounted : virtual private refcount { friend class refpriv; typedef typename type2struct::type obj_t; obj_t obj; // virtual void XXX_gcc_repo_workaround () {} // XXX - egcs bug operator T *() { return &static_cast (obj); } void refcount_call_finalize () { delete this; } ~refcounted () {} public: VA_TEMPLATE (explicit refcounted, : obj, {}) }; template class refcounted : virtual private refcount { friend class refpriv; typedef refcounted rc_t; virtual void XXX_gcc_repo_workaround () {} // XXX - egcs bug operator T *() { return tptr (this); } refcounted () { new ((void *) tptr (this)) T; } void refcount_call_finalize () { tptr (this)->~T (); delete this; } ~refcounted () {} public: static rc_t *alloc (size_t n) { return new (opnew (n + (size_t) tptr (NULL))) rc_t; } static T *tptr (rc_t *rcp) { return (T *) ((char *) rcp + ((sizeof (*rcp) + 7) & ~7)); } }; #define REFOPS_DEFAULT(T) \ protected: \ T *p; \ refops () {} \ \ public: \ T *get () const { return p; } \ operator T *() const { return p; } \ T *operator-> () const { return p; } \ T &operator* () const { return *p; } template class refops { REFOPS_DEFAULT (T) }; template<> class refops { protected: void *p; refops () {} public: operator void *() const { return p; } void *get () const { return p; } }; template class ref : public refpriv, public refops { friend class refpriv; using refops::p; friend ref mkref (T *); ref (T *pp, refcount *cc) : refpriv (cc) { p = pp; inc (); } void inc () const { rinc (c); } void dec () const { rdec (c); } public: typedef T type; typedef struct ptr ptr; template ref (refcounted *pp) : refpriv (rc (pp)) { p = refpriv::rp (pp); inc (); } /* At least with gcc, the copy constructor must be explicitly * defined (though it would appear to be redundant given the * template constructor bellow). */ ref (const ref &r) : refpriv (r.c) { p = r.p; inc (); } template ref (const ref &r) : refpriv (rc (r)) { p = refpriv::rp (r); inc (); } template ref (const ::ptr &r) : refpriv (rc (r)) { p = refpriv::rp (r); inc (); } ~ref () { dec (); } template ref &operator= (refcounted *pp) { rinc (pp); dec (); p = refpriv::rp (pp); c = rc (pp); return *this; } /* The copy assignment operator must also explicitly be defined, * despite a redundant template. */ ref &operator= (const ref &r) { r.inc (); dec (); p = r.p; c = r.c; return *this; } template ref &operator= (const ref &r) { rinc (r); dec (); p = refpriv::rp (r); c = rc (r); return *this; } /* Self asignment not possible. Use ref::inc to cause segfauls on NULL. */ template ref &operator= (const ::ptr &r) { dec (); p = refpriv::rp (r); c = rc (r); inc (); return *this; } }; /* To skip initialization of ptr's in BSS */ struct __bss_init {}; template class ptr : public refpriv, public refops { friend class refpriv; using refops::p; void inc () const { if (c) (rinc (c)); } void dec () const { if (c) (rdec (c)); } template void set (refcounted *pp, bool decme) { if (pp) { rinc (pp); if (decme) dec (); p = refpriv::rp (pp); c = rc (pp); } else { if (decme) dec (); p = NULL; c = NULL; } } public: typedef T type; typedef struct ref ref; explicit ptr (__bss_init) {} ptr () : refpriv (NULL) { p = NULL; } ptr (privtype *) : refpriv (NULL) { p = NULL; } template ptr (refcounted *pp) { set (pp, false); } ptr (const ptr &r) : refpriv (r.c) { p = r.p; inc (); } template ptr (const ptr &r) : refpriv (rc (r)) { p = refpriv::rp (r); inc (); } template ptr (const ::ref &r) : refpriv (rc (r)) { p = refpriv::rp (r); inc (); } ~ptr () { dec (); } ptr &operator= (privtype *) { dec (); p = NULL; c = NULL; return *this; } template ptr &operator= (refcounted *pp) { set (pp, true); return *this; } ptr &operator= (const ptr &r) { r.inc (); dec (); p = r.p; c = r.c; return *this; } template ptr &operator= (const ptr &r) { rinc (r); dec (); p = refpriv::rp (r); c = rc (r); return *this; } template ptr &operator= (const ::ref &r) { rinc (r); dec (); p = refpriv::rp (r); c = rc (r); return *this; } }; template struct bssptr : ptr { using ptr::Xleak; // Don't initialize (assume we were 0 initialized in the BSS) bssptr () : ptr (__bss_init ()) {} // Override the effects of destruction ~bssptr () { assert (globaldestruction); if (*this != NULL) Xleak (); } ptr &operator= (refpriv::privtype *p) { return ptr::operator= (p); } template ptr &operator= (const ptr &r) { return ptr::operator= (r); } template ptr &operator= (const ::ref &r) { return ptr::operator= (r); } }; template inline ref mkref (T *p) { return ref (p, p); } #endif /* !_REFCNT_H_INCLUDED_ */ avenger-0.8.5/libasync/stktrace.c0000644000175000017500000000733011221237220013657 00000000000000/* $Id$ */ /* * * Copyright (C) 2000 David Mazieres (dm@uun.org) * * 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 * */ #include "sysconf.h" #include #include #include #include #include #include #ifdef DMALLOC #include #endif /* DMALLOC */ #undef malloc #undef free #ifdef __OpenBSD__ # define NO_STACK_TOP 1 #endif /* OpenBSD */ int stktrace_record; #if __GNUC__ >= 2 && defined (__i386__) static const char hexdigits[] = "0123456789abcdef"; struct traceback { struct traceback *next; char *name; }; #define STKCACHESIZE 509U static struct traceback *stkcache[STKCACHESIZE]; #if NO_STACK_TOP static sigjmp_buf segv_env; static void segv_handler (int sig) { siglongjmp (segv_env, 1); } #endif /* NO_STACK_TOP */ const char * __backtrace (const char *file, int lim) { const void *const *framep; size_t filelen; char buf[256]; char *bp = buf + sizeof (buf); u_long bucket = 5381; struct traceback *tb; #if NO_STACK_TOP struct sigaction segv, osegv; #endif /* NO_STACK_TOP */ filelen = strlen (file); if (filelen >= sizeof (buf)) return file; bp -= filelen + 1; strcpy (bp, file); #if NO_STACK_TOP bzero (&segv, sizeof (segv)); segv.sa_handler = segv_handler; #ifdef SA_RESETHAND segv.sa_flags |= SA_RESETHAND; #endif /* SA_RESETHAND */ if (sigaction (SIGSEGV, &segv, &osegv) < 0) return file; #endif /* NO_STACK_TOP */ __asm volatile ("movl %%ebp, %0" : "=g" (framep) :); while (!((int) framep & 3) && (const char *) framep > buf && framep[0] && bp >= buf + 11 && lim--) { int i; u_long pc = (u_long) framep[1] - 1; bucket = ((bucket << 5) + bucket) ^ pc; *--bp = ' '; *--bp = hexdigits[pc & 0xf]; pc >>= 4; for (i = 0; pc && i < 7; i++) { *--bp = hexdigits[pc & 0xf]; pc >>= 4; } *--bp = 'x'; *--bp = '0'; #if NO_STACK_TOP if (sigsetjmp (segv_env, 0)) break; #endif /* NO_STACK_TOP */ framep = *framep; } #if NO_STACK_TOP sigaction (SIGSEGV, &osegv, NULL); #endif /* NO_STACK_TOP */ bucket = (bucket & 0xffffffff) % STKCACHESIZE; for (tb = stkcache[bucket]; tb; tb = tb->next) if (!strcmp (tb->name, bp)) return tb->name; tb = malloc (sizeof (*tb)); if (!tb) return file; tb->name = malloc (1 + strlen (bp)); if (!tb->name) { free (tb); return file; } strcpy (tb->name, bp); tb->next = stkcache[bucket]; stkcache[bucket] = tb; return tb->name; } #else /* !gcc 2 || !i386 */ const char * __backtrace (const char *file, int lim) { return file; } #endif /* !gcc 2 || !i386 */ #ifdef DMALLOC #if DMALLOC_VERSION_MAJOR < 5 #define dmalloc_logpath _dmalloc_logpath char *dmalloc_logpath; #endif /* DMALLOC_VERSION_MAJOR < 5 */ const char * stktrace (const char *file) { if (stktrace_record < 0) return file; else if (!stktrace_record) { if (!dmalloc_logpath || !(dmalloc_debug_current () & 2) || !getenv ("STKTRACE")) { stktrace_record = -1; return file; } stktrace_record = 1; } return __backtrace (file, -1); } #endif /* DMALLOC */ avenger-0.8.5/libasync/dnsparse.h0000644000175000017500000000753712260422177013707 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998-2003 David Mazieres (dm@uun.org) * * 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 _DNSPARSE_H_ #define _DNSPARSE_H_ 1 #include "dns.h" #include "qhash.h" #define QBSIZE 512 #ifndef T_DNAME # define T_DNAME 39 #endif /* !T_DNAME */ #ifndef T_SRV # define T_SRV 33 #endif /* !T_SRV */ #ifndef MAXDNAME # define MAXDNAME 1025 #endif /* !MAXDNAME */ class dnstcppkt { u_int inbufsize; u_int inbufpos; u_int inbufused; u_char *inbuf; suio outbuf; void compact (); u_int pktsize () { return inbufpos < inbufused + 2 ? 2 : getshort (inbuf + inbufused) + 2; } public: dnstcppkt (); ~dnstcppkt (); void reset (); int input (int fd); // Returns size of packet, 0 incomplete, -1 err int output (int fd); // 1 drained, 0 need again, -1 err bool getpkt (u_char **pp, size_t *sp); void putpkt (const u_char *p, size_t s); }; class nameset { typedef qhash map_t; u_int pos; map_t name2pos; public: nameset () : pos (0) {} char *store (str s); char *lookup (str s) const; bool present (str s) const { return name2pos[s]; } static char *xlat (char *base, char *p) { return base + (p - (char *) 0); } u_int size () const { return pos; } void put (char *dst) const; }; struct resrec { struct rd_mx { u_int16_t mx_pref; char mx_exch[MAXDNAME]; }; struct rd_soa { char soa_mname[MAXDNAME]; char soa_rname[MAXDNAME]; u_int32_t soa_serial; u_int32_t soa_refresh; u_int32_t soa_retry; u_int32_t soa_expire; u_int32_t soa_minimum; }; struct rd_srv { u_int16_t srv_prio; u_int16_t srv_weight; u_int16_t srv_port; char srv_target[MAXDNAME]; }; char rr_name[MAXDNAME]; u_int16_t rr_class; u_int16_t rr_type; u_int32_t rr_ttl; u_int16_t rr_rdlen; union { char rr_ns[MAXDNAME]; in_addr rr_a; char rr_cname[MAXDNAME]; rd_soa rr_soa; char rr_ptr[MAXDNAME]; rd_mx rr_mx; char rr_txt[sizeof (rd_soa)]; rd_srv rr_srv; }; }; struct question { char q_name[MAXDNAME]; u_int16_t q_class; u_int16_t q_type; }; class dnsparse { dnsparse (); const u_char *const buf; const u_char *const eom; const u_char *anp; static int mxrec_cmp (const void *, const void *); static int srvrec_cmp (const void *, const void *); static void srvrec_randomize (srvrec *base, srvrec *last); static size_t hintsize (u_int nhints) { return nhints * sizeof (addrhint) + (nhints+1) * sizeof (addrhint *); } static addrhint **puthints (char *dst, const vec &hv, char *namebase); bool gethints (vec *hv, const nameset &nset); public: int error; const HEADER *const hdr; const u_int ancount; const u_int nscount; const u_int arcount; dnsparse (const u_char *buf, size_t len, bool answer = true); const u_char *getqp () { return hdr ? buf + sizeof (HEADER) : NULL; } const u_char *getanp () { return anp; } bool qparse (question *); bool qparse (const u_char **, question *); bool rrparse (const u_char **, resrec *); bool skipnrecs (const u_char **, u_int); ptr tohostent (); ptr tomxlist (); ptr tosrvlist (); ptr totxtlist (); }; #endif /* !_DNSPARSE_H_ */ avenger-0.8.5/libasync/dns.C0000644000175000017500000004054012260430323012566 00000000000000/* $Id$ */ /* * * Copyright (C) 1998-2003 David Mazieres (dm@uun.org) * * 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 * */ /* Asynchronous resolver. This code is easy to understand if and only * if you also have a copy of RFC 1035. You can get this by anonymous * ftp from, among other places, ftp.internic.net:/rfc/rfc1035.txt. */ #include "dnsimpl.h" #include "arena.h" #include "vec.h" #include "ihash.h" #include "list.h" #include "backoff.h" #define RESOLV_CONF "/etc/resolv.conf" resolv_conf resconf; dnssock_udp::dnssock_udp (int f, cb_t cb) : dnssock (false, cb), fd (f) { fdcb (fd, selread, wrap (this, &dnssock_udp::rcb)); } dnssock_udp::~dnssock_udp () { fdcb (fd, selread, NULL); //fdcb (fd, selwrite, NULL); close (fd); } void dnssock_udp::sendpkt (const u_char *pkt, size_t size) { if (send (fd, pkt, size, 0) < 0 && errno != EAGAIN) (*cb) (NULL, -1); } void dnssock_udp::rcb () { ref d = destroyed; int n; do { u_char qb[QBSIZE]; n = recv (fd, reinterpret_cast (qb), sizeof (qb), 0); if (n > 0) (*cb) (qb, n); else if (!n || errno != EAGAIN) (*cb) (NULL, -1); } while (n > 0 && !*d); } dnssock_tcp::dnssock_tcp (int f, cb_t cb) : dnssock (true, cb), fd (f), write_ok (false) { fdcb (fd, selread, wrap (this, &dnssock_tcp::rcb)); fdcb (fd, selwrite, wrap (this, &dnssock_tcp::wcb, true)); } dnssock_tcp::~dnssock_tcp () { fdcb (fd, selread, NULL); fdcb (fd, selwrite, NULL); close (fd); } void dnssock_tcp::rcb () { if (tcpstate.input (fd) < 0) { (*cb) (NULL, -1); return; } ref d = destroyed; u_char *qb; size_t n; while (!*d && tcpstate.getpkt (&qb, &n)) (*cb) (qb, n); } void dnssock_tcp::wcb (bool selected) { if (selected) write_ok = true; if (!write_ok) return; int n = tcpstate.output (fd); if (n < 0) { fdcb (fd, selwrite, NULL); (*cb) (NULL, -1); } else if (n > 0) fdcb (fd, selwrite, NULL); else fdcb (fd, selwrite, wrap (this, &dnssock_tcp::wcb, true)); } void dnssock_tcp::sendpkt (const u_char *pkt, size_t size) { tcpstate.putpkt (pkt, size); wcb (); } resolver::resolver () : nbump (0), addr (NULL), addrlen (0), udpcheck_req (NULL), last_resp (0), last_bump (0), destroyed (New refcounted (false)) { #if NEWRES bzero (&res, sizeof (res)); res_ninit (&res); #else res_init(); #endif /* NEWRES */ } resolver::~resolver () { //cantsend (); // bad if exit called from callback delete udpcheck_req; *destroyed = true; } bool resolver::udpinit () { udpsock = NULL; int fd = socket (addr->sa_family, SOCK_DGRAM, 0); if (fd < 0) { warn ("resolver::udpsock: socket: %m\n"); return false; } make_async (fd); close_on_exec (fd); if (connect (fd, addr, addrlen) < 0) { warn ("resolver::udpsock: connect: %m\n"); close (fd); return false; } udpsock = New refcounted (fd, wrap (this, &resolver::pktready, false)); return true; } bool resolver::tcpinit () { tcpsock = NULL; int fd = socket (addr->sa_family, SOCK_STREAM, 0); if (fd < 0) { warn ("resolver::tcpsock: socket: %m\n"); return false; } make_async (fd); close_on_exec (fd); if (connect (fd, addr, addrlen) < 0 && errno != EINPROGRESS) { close (fd); return false; } tcpsock = New refcounted (fd, wrap (this, &resolver::pktready, true)); return true; } void resolver::cantsend () { ref d = destroyed; for (dnsreq *r = reqtab.first (), *nr; !*d && r; r = nr) { nr = reqtab.next (r); failreq (ARERR_CANTSEND, r); } } bool resolver::resend (bool udp, bool tcp) { ref d = destroyed; for (dnsreq *r = reqtab.first (), *nr; !*d && r; r = nr) { nr = reqtab.next (r); if (r->usetcp) { if (tcp && tcpsock) sendreq (r); else if (tcp) failreq (ARERR_CANTSEND, r); } else if (udp && udpsock) { reqtoq.remove (r); reqtoq.start (r); } } return !*d; } bool resolver::setsock (bool failure) { if (udpcheck_req) { delete udpcheck_req; udpcheck_req = NULL; } do { if ((failure || !addr) && !bumpsock (failure)) return false; failure = true; nbump++; last_resp = 0; last_bump = timenow; tcpsock = NULL; } while (!udpinit () || !tcpinit ()); return resend (true, true); } void resolver::sendreq (dnsreq *r) { if (!udpsock) { setsock (false); return; } ptr sock; if (!r->usetcp) sock = udpsock; else if (!tcpsock && !tcpinit ()) { setsock (true); return; } else sock = tcpsock; u_char qb[QBSIZE]; int n; #if NEWRES n = res_nmkquery (&res, QUERY, r->name, C_IN, r->type, NULL, 0, NULL, qb, sizeof (qb)); #else /* !NEWRES */ n = res_mkquery (QUERY, r->name, C_IN, r->type, NULL, 0, NULL, qb, sizeof (qb)); #endif /* !NEWRES */ //warn ("query (%s, %d): %d\n", r->name.cstr (), r->type, n); if (n < 0) { r->fail (ARERR_REQINVAL); return; } HEADER *const h = (HEADER *) qb; h->id = r->id; h->rd = 1; /* FreeBSD (and possibly other OSes) have a broken dn_expand * function that doesn't properly invert dn_comp. */ { dnsparse query (qb, n, false); question q; if (query.qparse (&q)) r->name = q.q_name; } sock->sendpkt (qb, n); } void resolver::pktready (bool tcp, u_char *qb, ssize_t n) { if (n <= 0) { if (tcp) { tcpsock = NULL; if (!last_resp) setsock (true); last_resp = 0; resend (false, true); } else { udpsock = NULL; setsock (true); } return; } nbump = 0; last_resp = timenow; dnsparse reply (qb, n); question q; if (!reply.qparse (&q) || q.q_class != C_IN) return; dnsreq *r; for (r = reqtab[reply.hdr->id]; r && (r->usetcp != tcp || r->type != q.q_type || strcasecmp (r->name, q.q_name)); r = reqtab.nextkeq (r)) ; if (!r) return; if (reply.error && !r->error) r->error = reply.error; if (r->error == NXDOMAIN) { r->error = 0; r->start (true); } else if (!r->error && !r->usetcp && reply.hdr->tc) { reqtoq.remove (r); r->usetcp = true; r->xmit (0); } else r->readreply (r->error ? NULL : &reply); } u_int16_t resolver::genid () { u_int16_t id; int i = 0; do { id = arandom () % 0xffff; } while (reqtab[id] && ++i < 8); return id; } void resolver::udpcheck () { if (!udpcheck_req) udpcheck_req = New dnsreq_a (this, "", wrap (this, &resolver::udpcheck_cb), false); } void resolver::udpcheck_cb (ptr h, int err) { udpcheck_req = NULL; if (err == ARERR_TIMEOUT) setsock (true); } resolv_conf::resolv_conf () : ns_idx (0), last_reload (0), destroyed (New refcounted (false)), resolv_conf_path (RESOLV_CONF) { bzero (&lastresconf, sizeof (lastresconf)); stat (resolv_conf_path, &lastresconf); parse_resolv_conf (&resconf, resolv_conf_path, true); ifc = ifchgcb (wrap (this, &resolv_conf::reload, false)); if (int n = resconf.resolvers.size()) ns_idx = n - 1; } resolv_conf::~resolv_conf () { *destroyed = true; ifchgcb_remove (ifc); } void resolv_conf::reload (bool failure) { struct stat sb; bzero (&sb, sizeof (sb)); stat (resolv_conf_path, &sb); last_reload = timenow; nbump = 0; if (sb.st_mtime != lastresconf.st_mtime || sb.st_ctime != lastresconf.st_ctime) { lastresconf = sb; parse_resolv_conf (&resconf, resolv_conf_path); if ((ns_idx = resconf.resolvers.size ()) > 0) ns_idx--; setsock (true); } else setsock (failure); } bool resolv_conf::bumpsock (bool failure) { if (timenow > last_reload + 60) { reload (failure); return false; } if (unsigned (nbump) >= resconf.resolvers.size()) { cantsend (); return false; } ns_idx = (ns_idx + 1) % resconf.resolvers.size(); const sockaddr_storage &newserver = resconf.resolvers[ns_idx]; if (failure && (!addr || !addreq (addr, reinterpret_cast (&newserver), addrlen))) warn ("changing nameserver to %s\n", satostr (&newserver).cstr()); addr = reinterpret_cast (&newserver); addrlen = resconf.resolvers_sa_len[ns_idx]; return true; } const char * resolv_conf::srchlist (int n) { if (n <= 0) return ""; else if (unsigned (n) > resconf.searchlist.size()) return NULL; return resconf.searchlist[n - 1]; } dnsreq::dnsreq (resolver *rp, str n, u_int16_t t, bool search) : ntries (0), resp (rp), usetcp (false), constructed (false), error (0), type (t) { while (n.len () && n[n.len () - 1] == '.') { search = false; n = substr (n, 0, n.len () - 1); } if (!search) { srchno = -1; basename = NULL; name = n; } else { srchno = 0; basename = n; name = NULL; } start (false); constructed = true; } void dnsreq::remove () { if (intable) { intable = false; resp->reqtab.remove (this); if (!usetcp) resp->reqtoq.remove (this); } } dnsreq::~dnsreq () { remove (); } void dnsreq::start (bool again) { if (again && (srchno < 0 || !resp->srchlist (srchno))) { fail (NXDOMAIN); return; } if (again) { resp->reqtab.remove (this); if (!usetcp) resp->reqtoq.remove (this); } if (srchno >= 0) { const char *suffix = resp->srchlist (srchno++); if (*suffix) name = strbuf ("%s.%s", basename.cstr (), suffix); else name = basename; } id = resp->genid (); intable = true; resp->reqtab.insert (this); if (usetcp) xmit (0); else resp->reqtoq.start (this); } void dnsreq::xmit (int retry) { error = 0; resp->sendreq (this); } void dnsreq::timeout () { assert (!usetcp); if (timenow - resp->last_resp < 90 || !name.len ()) fail (ARERR_TIMEOUT); else { resp->reqtoq.keeptrying (this); resp->udpcheck (); } } void dnsreq::fail (int err) { assert (err); if (!error) error = err; if (constructed) readreply (NULL); else { remove (); delaycb (0, wrap (this, &dnsreq::readreply, (dnsparse *) NULL)); } } void dnsreq_cancel (dnsreq *rqp) { delete rqp; } void dnsreq_a::readreply (dnsparse *reply) { ptr h; if (!error) { assert (reply); if (!(h = reply->tohostent ())) error = reply->error; else if (checkaddr) { char **ap; for (ap = h->h_addr_list; *ap && *(in_addr *) *ap != addr; ap++) ; if (!*ap) { h = NULL; error = ARERR_PTRSPOOF; } } } (*cb) (h, error); delete this; } dnsreq * dns_hostbyname (str name, cbhent cb, bool search, bool addrok) { if (addrok) { in_addr addr; if (name.len () && isdigit (name[name.len () - 1]) && inet_aton (name.cstr (), &addr)) { ptr h = refcounted::alloc (sizeof (*h) + 3 * sizeof (void *) + sizeof (addr) + strlen (name) + 1); h->h_aliases = (char **) &h[1]; h->h_addrtype = AF_INET; h->h_length = sizeof (addr); h->h_addr_list = &h->h_aliases[1]; h->h_aliases[0] = NULL; h->h_addr_list[0] = (char *) &h->h_addr_list[2]; h->h_addr_list[1] = NULL; *(struct in_addr *) h->h_addr_list[0] = addr; h->h_name = (char *) h->h_addr_list[0] + sizeof (addr); strcpy ((char *) h->h_name, name); (*cb) (h, 0); return NULL; } } return New dnsreq_a (&resconf, name, cb, search); } void dnsreq_mx::readreply (dnsparse *reply) { ptr m; if (!error) { if (!(m = reply->tomxlist ())) error = reply->error; } (*cb) (m, error); delete this; } dnsreq * dns_mxbyname (str name, cbmxlist cb, bool search) { return New dnsreq_mx (&resconf, name, cb, search); } void dnsreq_srv::readreply (dnsparse *reply) { ptr s; if (!error) { if (!(s = reply->tosrvlist ())) error = reply->error; } (*cb) (s, error); delete this; } dnsreq * dns_srvbyname (str name, cbsrvlist cb, bool search) { return New dnsreq_srv (&resconf, name, cb, search); } dnsreq_ptr::~dnsreq_ptr () { while (!vrfyv.empty ()) delete vrfyv.pop_front (); } void dnsreq_ptr::maybe_push (vec *sv, const char *s) { for (const str *sp = sv->base (); sp < sv->lim (); sp++) if (!strcasecmp (sp->cstr (), s)) return; sv->push_back (s); } str dnsreq_ptr::inaddr_arpa (in_addr addr) { u_char *a = reinterpret_cast (&addr); return strbuf ("%d.%d.%d.%d.in-addr.arpa", a[3], a[2], a[1], a[0]); } void dnsreq_ptr::readreply (dnsparse *reply) { vec names; if (!error) { const u_char *cp = reply->getanp (); for (u_int i = 0; i < reply->ancount; i++) { resrec rr; if (!reply->rrparse (&cp, &rr)) break; if (rr.rr_type == T_PTR && rr.rr_class == C_IN) maybe_push (&names, rr.rr_ptr); } if (!names.empty ()) { napending = names.size (); remove (); for (u_int i = 0; i < names.size (); i++) vrfyv.push_back (New dnsreq_a (resp, names[i], wrap (this, &dnsreq_ptr::readvrfy, i), addr)); return; } } if (!error && !(error = reply->error)) error = ARERR_NXREC; (*cb) (NULL, error); delete this; } void dnsreq_ptr::readvrfy (int i, ptr h, int err) { vrfyv[i] = NULL; if (err && (dns_tmperr (err) || !error)) error = err; if (h) { maybe_push (&vnames, h->h_name); for (char **np = h->h_aliases; *np; np++) maybe_push (&vnames, *np); } if (--napending) return; if (vnames.empty () && !error) error = ARERR_PTRSPOOF; if (error) { (*cb) (NULL, error); delete this; return; } u_int namelen = 0; for (str *np = vnames.base (); np < vnames.lim (); np++) namelen += np->len () + 1; int hsize = (sizeof (*h) + (vnames.size () + 1) * sizeof (char *) + namelen + 2 * sizeof (char *) + sizeof (in_addr)); h = refcounted::alloc (hsize); h->h_addrtype = AF_INET; h->h_length = sizeof (in_addr); h->h_aliases = (char **) &h[1]; h->h_addr_list = &h->h_aliases[vnames.size ()]; h->h_addr_list[0] = (char *) &h->h_addr_list[2]; h->h_addr_list[1] = NULL; *(in_addr *) h->h_addr_list[0] = addr; char *dp = h->h_addr_list[0] + sizeof (in_addr); h->h_name = dp; memcpy (dp, vnames[0], vnames[0].len () + 1); dp += vnames[0].len () + 1; vnames.pop_front (); char **ap = h->h_aliases; while (!vnames.empty ()) { *ap = dp; memcpy (dp, vnames.front (), vnames.front ().len () + 1); dp += vnames.front ().len () + 1; ap++; vnames.pop_front (); } *ap = NULL; (*cb) (h, error); delete this; } dnsreq * dns_hostbyaddr (in_addr addr, cbhent cb) { return New dnsreq_ptr (&resconf, addr, cb); } void dnsreq_txt::readreply (dnsparse *reply) { ptr t; if (!error && !(t = reply->totxtlist ())) error = reply->error; (*cb) (t, error); delete this; } dnsreq_t * dns_txtbyname (str name, cbtxtlist cb, bool search) { return New dnsreq_txt (&resconf, name, cb, search); } const char * dns_strerror (int no) { switch (no) { case NOERROR: return "no error"; case FORMERR: return "DNS format error"; case SERVFAIL: return "name server failure"; case NXDOMAIN: return "non-existent domain name"; case NOTIMP: return "unimplemented DNS request"; case REFUSED: return "DNS query refused"; case ARERR_NXREC: return "no DNS records of appropriate type"; case ARERR_TIMEOUT: return "name lookup timed out"; case ARERR_PTRSPOOF: return "incorrect PTR record"; case ARERR_BADRESP: return "malformed DNS reply"; case ARERR_CANTSEND: return "cannot send to name server"; case ARERR_REQINVAL: return "malformed domain name"; case ARERR_CNAMELOOP: return "CNAME records form loop"; default: return "unknown DNS error"; } } int dns_tmperr (int no) { switch (no) { case SERVFAIL: case ARERR_TIMEOUT: case ARERR_CANTSEND: case ARERR_BADRESP: return 1; default: return 0; } } avenger-0.8.5/libasync/dns.h0000644000175000017500000000720112260422177012640 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998-2003 David Mazieres (dm@uun.org) * * 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 _DNS_H_ #define _DNS_H_ 1 #include "async.h" extern "C" { #define class rr_class #if HAVE_ARPA_NAMESER_COMPAT_H #include #include #else /* !HAVE_ARPA_NAMESER_COMPAT_H */ #include #endif /* !HAVE_ARPA_NAMESER_COMPAT_H */ #undef class #include /* Declarations missing on some OS's */ #ifdef NEED_RES_INIT_DECL void res_init (); #endif /* NEED_RES_INIT_DECL */ #ifdef NEED_RES_MKQUERY_DECL int res_mkquery (int, const char *, int, int, const u_char *, int, const u_char *, u_char *, int); #endif /* NEED_RES_MKQUERY_DECL */ } struct addrhint { char *h_name; int h_addrtype; int h_length; char h_address[16]; }; // struct hostent; struct mxrec { u_int16_t pref; char *name; }; struct mxlist { char *m_name; /* Name of host for which MX list taken */ struct addrhint **m_hints; u_short m_nmx; /* Number of mx records */ struct mxrec m_mxes[1]; /* MX records */ }; struct srvrec { u_int16_t prio; u_int16_t weight; u_int16_t port; char *name; }; struct srvlist { char *s_name; struct addrhint **s_hints; u_short s_nsrv; struct srvrec s_srvs[1]; }; struct txtlist { char *t_name; u_short t_ntxt; char *t_txts[1]; }; /* Extender error types for ar_errno */ #define ARERR_NXREC 0x101 /* No records of appropriate type */ #define ARERR_TIMEOUT 0x102 /* Query timed out */ #define ARERR_PTRSPOOF 0x103 /* PTR response was a lie! */ #define ARERR_BADRESP 0x104 /* Nameserver replied with malformed packet */ #define ARERR_CANTSEND 0x105 /* Can't send to name server */ #define ARERR_REQINVAL 0x106 /* Request was for malformed domain name */ #define ARERR_CNAMELOOP 0x107 /* CNAME records form loop */ typedef struct dnsreq dnsreq_t; void dnsreq_cancel (dnsreq_t *rqp); typedef callback, int>::ref cbhent; dnsreq_t *dns_hostbyname (str, cbhent, bool search = false, bool addrok = true); dnsreq_t *dns_hostbyaddr (const in_addr, cbhent); typedef callback, int>::ref cbmxlist; dnsreq_t *dns_mxbyname (str, cbmxlist, bool search = false); typedef callback, int>::ref cbsrvlist; dnsreq_t *dns_srvbyname (str name, cbsrvlist, bool search = false); typedef callback, int>::ref cbtxtlist; dnsreq_t *dns_txtbyname (str name, cbtxtlist cb, bool search = false); inline dnsreq_t * dns_srvbyname (const char *name, const char *proto, const char *srv, cbsrvlist cb, bool search = false) { return dns_srvbyname (strbuf ("_%s._%s.%s", srv, proto, name), cb, search); } const char *dns_strerror (int); int dns_tmperr (int); void printaddrs (const char *, ptr, int = 0); void printmxlist (const char *, ptr, int = 0); void printsrvlist (const char *msg, ptr s, int = 0); void printtxtlist (const char *msg, ptr s, int = 0); void dns_reload (); #endif /* !_DNS_H_ */ avenger-0.8.5/libasync/arena.C0000644000175000017500000000252311221237220013064 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "arena.h" #include "msb.h" void arena::newchunk (size_t bytes) { char *c; #ifndef DMALLOC if (bytes < size) bytes = size; size = (1 << (log2c (bytes + MALLOCRESV) + 1)) - MALLOCRESV; #else /* DMALLOC */ /* Malloc each chunk seperately so dmalloc catches overrun bugs */ size = bytes + resv; #endif /* DMALLOC */ avail = size - resv; c = (char *) xmalloc (size); *(void **) c = chunk; chunk = c; cur = c + resv; assert (bytes <= avail); } arena::~arena () { void *p, *np; for (p = chunk; p; p = np) { np = *(void **) p; xfree (p); } } avenger-0.8.5/libasync/init.h0000644000175000017500000000330411221237220013004 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_INIT_H_ #define _ASYNC_INIT_H_ 1 #if __GNUC__ >= 3 # define __init_attribute__(x) #else /* gcc < 3 */ # define __init_attribute__(x) __attribute__ (x) #endif /* gcc < 3 */ #define INIT(name) \ static class name { \ static int count; \ static int &cnt () { return count; } \ static void start (); \ static void stop (); \ public: \ name () {if (!cnt ()++) start ();} \ ~name () {if (!--cnt ()) stop ();} \ } init_ ## name __init_attribute__ ((unused)) class initfn { initfn (); public: initfn (void (*fn) ()) { fn (); } }; #define INITFN(fn) \ static void fn (); \ static initfn init_ ## fn (fn) __init_attribute__ ((unused)) class exitfn { void (*const fn) (); public: exitfn (void (*fn) ()) : fn (fn) {} ~exitfn () { fn (); } }; #define EXITFN(fn) \ static void fn (); \ static exitfn exit_ ## fn (fn) __init_attribute__ ((unused)) #endif /* !_ASYNC_INIT_H_ */ avenger-0.8.5/libasync/array.h0000644000175000017500000000624611221237220013167 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ /* ***** WHY: * * C arrays (e.g. "int c[64];") vastly complicate some aspects of C++ * template programming. Suppose you have a template tmpl with a * class parameter T, and T is instantiated with an array: * * class elm { * //... * }; * * template tmpl { * //... * }; * * typedef tmpl problem_t; * * If, for instance, tmpl generally needs to allocate an object of * type T, a function in tmpl might have code like this: * * T *objp = new T; * * However, this won't work when T is elm[64], because the code * "new elm[64]" returns an "elm *", not a "(*) elm[64]". * * Worse yet, any code that uses placement new or calls destructors * will not work. If T is an array, then allocating a "new T" invokes * operator new[] rather than operator new, and that generally * requires more than sizeof(T) bytes. * * Finally, a lot of template classes require things like copy * constructors or assignment to work, and neither of those does with * C arrays. * * * ***** WHAT: * * The simple solution to all these problems is simply not to use C * arrays. The dirt-simple type "array" is simply an * array wrapped in a structure. These arrays can be allocated with * the ordinary scalar new, and things like assignment and copy * construction will work fine. * * The macro "toarray" converts a C array type to a template array. */ #ifndef _ARRAY_H_WITH_TOARRAY_ #define _ARRAY_H_WITH_TOARRAY_ 1 #include template struct array; template struct __toarray { typedef T type; }; template struct __toarray { typedef array::type, n> type; }; #define toarray(T) __toarray::type template class array { public: typedef typename toarray(T) elm_t; enum { nelm = n }; private: elm_t a[nelm]; #ifdef CHECK_BOUNDS void bcheck (size_t i) const { assert (i < nelm); } #else /* !CHECK_BOUNDS */ void bcheck (size_t) const {} #endif /* !CHECK_BOUNDS */ public: static size_t size () { return nelm; } elm_t *base () { return a; } const elm_t *base () const { return a; } elm_t *lim () { return a + nelm; } const elm_t *lim () const { return a + nelm; } elm_t &operator[] (ptrdiff_t i) { bcheck (i); return a[i]; } const elm_t &operator[] (ptrdiff_t i) const { bcheck (i); return a[i]; } }; #endif /* _ARRAY_H_WITH_TOARRAY_ */ avenger-0.8.5/libasync/armor.C0000644000175000017500000002424511221237220013123 00000000000000/* $Id$ */ /* * * Copyright (C) 1999 David Mazieres (dm@uun.org) * * 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 * */ #include "serial.h" static const char b2a32[32] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9', }; static const signed char a2b32[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, 26, 27, 28, 29, 30, 31, -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, 10, -1, 11, 12, -1, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; static const int b2a32rem[5] = {0, 2, 4, 5, 7}; static const int a2b32rem[8] = {0, -1, 1, -1, 2, 3, -1, 4}; /* 0 1 2 3 4 5 6 7 * 0 5 3 * 1 2 5 1 * 2 4 4 * 3 1 5 2 * 4 3 5 */ str armor32 (const void *dp, size_t dl) { const u_char *p = static_cast (dp); int rem = dl % 5; const u_char *e = p + (dl - rem); mstr res ((dl / 5) * 8 + b2a32rem[rem]); char *d = res; while (p < e) { d[0] = b2a32[p[0] >> 3]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[3] = b2a32[(p[1] & 0x1) << 4 | p[2] >> 4]; d[4] = b2a32[(p[2] & 0xf) << 1 | p[3] >> 7]; d[5] = b2a32[p[3] >> 2 & 0x1f]; d[6] = b2a32[(p[3] & 0x3) << 3 | p[4] >> 5]; d[7] = b2a32[p[4] & 0x1f]; p += 5; d += 8; } switch (rem) { case 4: d[6] = b2a32[(p[3] & 0x3) << 3]; d[5] = b2a32[p[3] >> 2 & 0x1f]; d[4] = b2a32[(p[2] & 0xf) << 1 | p[3] >> 7]; d[3] = b2a32[(p[1] & 0x1) << 4 | p[2] >> 4]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[0] = b2a32[p[0] >> 3]; d += 7; break; case 3: d[4] = b2a32[(p[2] & 0xf) << 1]; d[3] = b2a32[(p[1] & 0x1) << 4 | p[2] >> 4]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[0] = b2a32[p[0] >> 3]; d += 5; break; case 2: d[3] = b2a32[(p[1] & 0x1) << 4]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[0] = b2a32[p[0] >> 3]; d += 4; break; case 1: d[1] = b2a32[(p[0] & 0x7) << 2]; d[0] = b2a32[p[0] >> 3]; d += 2; break; } assert (d == res + res.len ()); return res; } size_t armor32len (const u_char *s) { const u_char *p = s; while (a2b32[*p] >= 0) p++; return p - s; } str dearmor32 (const char *_s, ssize_t len) { const u_char *s = reinterpret_cast (_s); if (len < 0) len = armor32len (s); int rem = a2b32rem[len & 7]; if (rem < 0) return NULL; if (!len) return ""; mstr bin ((len >> 3) * 5 + rem); char *d = bin; int c0, c1, c2, c3, c4, c5, c6, c7; for (const u_char *e = s + (len & ~7); s < e; s += 8, d += 5) { c0 = a2b32[s[0]]; c1 = a2b32[s[1]]; d[0] = c0 << 3 | c1 >> 2; c2 = a2b32[s[2]]; c3 = a2b32[s[3]]; d[1] = c1 << 6 | c2 << 1 | c3 >> 4; c4 = a2b32[s[4]]; d[2] = c3 << 4 | c4 >> 1; c5 = a2b32[s[5]]; c6 = a2b32[s[6]]; d[3] = c4 << 7 | c5 << 2 | c6 >> 3; c7 = a2b32[s[7]]; d[4] = c6 << 5 | c7; } if (rem >= 1) { c0 = a2b32[s[0]]; c1 = a2b32[s[1]]; *d++ = c0 << 3 | c1 >> 2; if (rem >= 2) { c2 = a2b32[s[2]]; c3 = a2b32[s[3]]; *d++ = c1 << 6 | c2 << 1 | c3 >> 4; if (rem >= 3) { c4 = a2b32[s[4]]; *d++ = c3 << 4 | c4 >> 1; if (rem >= 4) { c5 = a2b32[s[5]]; c6 = a2b32[s[6]]; *d++ = c4 << 7 | c5 << 2 | c6 >> 3; } } } } assert (d == bin + bin.len ()); return bin; } static const char b2a64[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; static const signed char a2b64[256] = { -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, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; inline str _armor64 (const char *b2a, bool endpad, const void *dp, size_t len) { const u_char *p = static_cast (dp); int rem = len % 3; const u_char *e = p + (len - rem); mstr res (((len + 2) / 3) * 4); char *d = res; while (p < e) { d[0] = b2a[p[0] >> 2]; d[1] = b2a[(p[0] & 0x3) << 4 | p[1] >> 4]; d[2] = b2a[(p[1] & 0xf) << 2 | p[2] >> 6]; d[3] = b2a[p[2] & 0x3f]; d += 4; p += 3; } switch (rem) { case 1: d[0] = b2a[p[0] >> 2]; d[1] = b2a[(p[0] & 0x3) << 4]; d[2] = d[3] = '='; d += 4; break; case 2: d[0] = b2a[p[0] >> 2]; d[1] = b2a[(p[0] & 0x3) << 4 | p[1] >> 4]; d[2] = b2a[(p[1] & 0xf) << 2]; d[3] = '='; d += 4; break; } assert (d == res + res.len ()); if (!endpad && rem) res.setlen (res.len () + rem - 3); return res; } str armor64 (const void *s, size_t len) { return _armor64 (b2a64, true, s, len); } inline str _dearmor64 (const signed char *a2b, const u_char *s, ssize_t len) { if (!len) return ""; mstr bin (len - (len>>2)); char *d = bin; int c0, c1, c2, c3; for (const u_char *e = s + len - 4; s < e; s += 4, d += 3) { c0 = a2b[s[0]]; c1 = a2b[s[1]]; d[0] = c0 << 2 | c1 >> 4; c2 = a2b[s[2]]; d[1] = c1 << 4 | c2 >> 2; c3 = a2b[s[3]]; d[2] = c2 << 6 | c3; } c0 = a2b[s[0]]; c1 = a2b[s[1]]; *d++ = c0 << 2 | c1 >> 4; if ((c2 = a2b[s[2]]) >= 0) { *d++ = c1 << 4 | c2 >> 2; if ((c3 = a2b[s[3]]) >= 0) *d++ = c2 << 6 | c3; } bin.setlen (d - bin); return bin; } size_t armor64len (const u_char *s) { const u_char *p = s; while (a2b64[*p] >= 0) p++; if (*p == '=') p++; if (*p == '=') p++; return p - s; } str dearmor64 (const char *_s, ssize_t len) { const u_char *s = reinterpret_cast (_s); if (len < 0) len = armor64len (s); if (len & 3) return NULL; return _dearmor64 (a2b64, s, len); } static const char b2a64A[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', }; static const signed char a2b64A[256] = { -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, 62, -1, 63, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; str armor64A (const void *s, size_t len) { return _armor64 (b2a64A, false, s, len); } size_t armor64Alen (const u_char *s) { const u_char *p = s; while (a2b64A[*p] >= 0) p++; return p - s; } str dearmor64A (const char *_s, ssize_t len) { const u_char *s = reinterpret_cast (_s); if (len < 0) len = armor64Alen (s); return _dearmor64 (a2b64A, s, len); } avenger-0.8.5/libasync/msb.h0000644000175000017500000000542411221237220012627 00000000000000/* -*-c++-*- */ /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _MSB_H_ #define _MSB_H_ 1 #include "sysconf.h" #ifdef __cplusplus #define EXTERN_C extern "C" #else /* !__cplusplus */ #define EXTERN_C extern #endif /* !__cplusplus */ /* * Routines for calculating the most significant bit of an integer. */ EXTERN_C const char bytemsb[]; /* Find last set (most significant bit) */ static inline u_int fls32 (u_int32_t) __attribute__ ((const)); static inline u_int fls32 (u_int32_t v) { if (v & 0xffff0000) { if (v & 0xff000000) return 24 + bytemsb[v>>24]; else return 16 + bytemsb[v>>16]; } if (v & 0x0000ff00) return 8 + bytemsb[v>>8]; else return bytemsb[v]; } /* Ceiling of log base 2 */ static inline int log2c32 (u_int32_t) __attribute__ ((const)); static inline int log2c32 (u_int32_t v) { return v ? (int) fls32 (v - 1) : -1; } static inline u_int fls64 (u_int64_t) __attribute__ ((const)); static inline u_int fls64 (u_int64_t v) { u_int32_t h; if ((h = v >> 32)) return 32 + fls32 (h); else return fls32 ((u_int32_t) v); } static inline int log2c64 (u_int64_t) __attribute__ ((const)); static inline int log2c64 (u_int64_t v) { return v ? (int) fls64 (v - 1) : -1; } #define fls(v) (sizeof (v) > 4 ? fls64 (v) : fls32 (v)) #define log2c(v) (sizeof (v) > 4 ? log2c64 (v) : log2c32 (v)) /* * For symmetry, a 64-bit find first set, "ffs," that finds the least * significant 1 bit in a word. */ EXTERN_C const char bytelsb[]; static inline u_int ffs32 (u_int32_t v) { if (v & 0xffff) { if (int vv = v & 0xff) return bytelsb[vv]; else return 8 + bytelsb[v >> 8 & 0xff]; } else if (int vv = v & 0xff0000) return 16 + bytelsb[vv >> 16]; else if (v) return 24 + bytelsb[v >> 24 & 0xff]; else return 0; } static inline u_int ffs64 (u_int64_t v) { u_int32_t l; if ((l = v & 0xffffffff)) return fls32 (l); else if ((l = v >> 32)) return 32 + fls32 (l); else return 0; } #define ffs(v) (sizeof (v) > 4 ? ffs64 (v) : ffs32 (v)) #undef EXTERN_C #endif /* _MSB_H_ */ avenger-0.8.5/libasync/ifchg.C0000644000175000017500000000370111221237220013055 00000000000000/* $Id$ */ /* * * Copyright (C) 2002 David Mazieres (dm@uun.org) * * 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 * */ #include "async.h" #include "dns.h" #include "list.h" vec ifchg_addrs; u_int64_t ifchg_count = 1; struct ifchgcb_t { const cbv cb; list_entry link; ifchgcb_t (cbv c); ~ifchgcb_t (); }; static list chglist; static lazycb_t *lazy; ifchgcb_t::ifchgcb_t (cbv c) : cb (c) { } ifchgcb_t::~ifchgcb_t () { list::remove (this); } void ifchgcb_test () { vec newaddrs; if (!myipaddrs (&newaddrs)) return; if (newaddrs.size () == ifchg_addrs.size () && !memcmp (newaddrs.base (), ifchg_addrs.base (), ifchg_addrs.size () * sizeof (in_addr))) return; ifchg_addrs.swap (newaddrs); ++ifchg_count; list olist; chglist.swap (olist); while (ifchgcb_t *chg = olist.first) { olist.remove (chg); chglist.insert_head (chg); (*chg->cb) (); } } ifchgcb_t * ifchgcb (cbv cb) { if (!lazy) { if (!myipaddrs (&ifchg_addrs)) fatal ("myipaddrs: %m\n"); lazy = lazycb (60, wrap (ifchgcb_test)); } ifchgcb_t *chg = New ifchgcb_t (cb); chglist.insert_head (chg); return chg; } void ifchgcb_remove (ifchgcb_t *chg) { delete chg; } avenger-0.8.5/libasync/aios.h0000644000175000017500000001162311221237220012777 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_AIOS_H_ #define _ASYNC_AIOS_H_ 1 #include "str.h" #include "union.h" #include "init.h" #include "cbuf.h" struct timecb_t; INIT(aiosinit); class aios : virtual public refcount { friend class aiosout; typedef callback::ptr rcb_t; typedef callback::ptr wcb_t; bool rlock; bool (aios::*infn) (); rcb_t rcb; bool wblock; time_t timeoutval; time_t timeoutnext; timecb_t *timeoutcb; ssize_t debugiov; vec fdsendq; void mkrcb (const str &s) { infn = &aios::rnone; rcb_t::ref cb = rcb; rcb = NULL; (*cb) (s, err); } void timeoutcatch (); void timeoutbump (); bool rnone () { return false; } bool rline (); bool rany (); void setreadcb (bool (aios::*fn) (), rcb_t cb); virtual void mkwcb (wcb_t cb) { if (fd >= 0) (*cb) (err); } void schedwrite (); void dumpdebug (); void outstart () { assert (!weof); if (debugname) { outb.tosuio ()->breakiov (); debugiov = outb.tosuio ()->iovcnt (); } } void outstop () { if (debugname) dumpdebug (); debugiov = -1; schedwrite (); } protected: int fd; cbuf inb; strbuf outb; int err; bool eof; bool weof; str debugname; const char *wrpref; const char *rdpref; const char *errpref; aios (int, size_t); ~aios (); void finalize (); bool reading () { return rcb; } virtual bool writing () { return outb.tosuio ()->resid (); } void fail (int e); void input (); void (output) (); virtual int doinput (); virtual int dooutput (); virtual void setincb (); virtual void setoutcb (); public: enum { defrbufsize = 0x2000 }; static ref alloc (int fd, size_t rbsz = defrbufsize) { return New refcounted (fd, rbsz); } int fdno () { return fd; } void setdebug (str name) { debugname = name; } void settimeout (time_t secs) { timeoutval = secs; timeoutbump (); } time_t gettimeout () { return timeoutval; } void abort (); void setrbufsize (size_t n) { inb.resize (n); } size_t getrbufbytes () { return inb.bytes (); } void readline (rcb_t cb) { setreadcb (&aios::rline, cb); } void readany (rcb_t cb) { setreadcb (&aios::rany, cb); } void readcancel () { infn = &aios::rnone; rcb = NULL; } void unread (size_t n) { inb.unrembytes (n); } void writev (const iovec *iov, int iovcnt); void write (void *buf, size_t len) { iovec iov = { iovbase_t (buf), len }; writev (&iov, 1); } void sendeof (); virtual void setwcb (wcb_t cb) { suio_callback (outb.tosuio (), wrap (this, &aios::mkwcb, cb)); } int flush (); void sendfd (int sfd) { fdsendq.push_back (sfd); } }; typedef ref aios_t; class aiosout : public strbuf { aios *s; // aiosout (aiosout &o) : strbuf (o), s (o.s) { o.s = NULL; } aiosout &operator= (const aiosout &); public: /* XXX - We intentionally make the copy constructor public and * undefined, because aiosout objects cannot be copied. No * reasonable compiler should copy an aiosout during reference copy * initialization (e.g., ``aout << "hello world\n";''). However, * section 8.5.3/5 of the C++ standard implies the compiler is * allowed to make copies of an aios object during reference copy * initialization, because it can make and initialize a temporary * aiosout using copy (not direct) initialization from the const * aios_t &. Section 12.1/1 therefore requires that the copy * constructor be accessible, so we can't make it private either. */ aiosout (const aiosout &o); aiosout (const aios_t &a) : strbuf (a->outb), s(a) { s->outstart (); } aiosout (const aios_t::ptr &a) : strbuf (a->outb), s(a) { s->outstart (); } ~aiosout () { s->outstop (); } }; template inline const strbuf & operator<< (const aiosout &o, const T &a) { return strbuf_cat (o, a); } inline const strbuf & operator<< (const aiosout &o, const str &s) { suio_print (o.tosuio (), s); return o; } // XXX - gcc bug requires this: inline const strbuf & operator<< (const aiosout &o, const char *a) { return strbuf_cat (o, a); } // extern const str endl; #ifndef __AIOS_IMPLEMENTATION extern aios_t ain, aout; #endif /* !__AIOS_IMPLEMENTATION */ #endif /* !_ASYNC_AIOS_H_ */ avenger-0.8.5/libasync/myaddrs.C0000644000175000017500000000515711340350230013446 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "amisc.h" #include "qhash.h" #include #ifdef HAVE_SYS_SOCKIO_H #include #endif /* HAVE_SYS_SOCKIO_H */ #define MAXCONFBUF 0x10000 bool myipaddrs (vec *res) { static u_int len = 512; struct ifconf ifc; char *p, *e; int s; if ((s = socket (AF_INET, SOCK_DGRAM, 0)) < 0) { warn ("socket: %m\n"); return false; } errno = 0; ifc.ifc_len = MAXCONFBUF; ifc.ifc_buf = NULL; for (;;) { ifc.ifc_len = len; xfree (ifc.ifc_buf); ifc.ifc_buf = (char *) xmalloc (ifc.ifc_len); if (ioctl (s, SIOCGIFCONF, &ifc) < 0) { warn ("SIOCGIFCONF: %m\n"); close (s); xfree (ifc.ifc_buf); return false; } /* The +64 is for large addresses (e.g., IPv6), in which sa_len * may be greater than the struct sockaddr inside ifreq. */ if (ifc.ifc_len + sizeof (struct ifreq) + 64 < len) break; len *= 2; if (len >= MAXCONFBUF) { warn ("SIOCGIFCONF: buffer too large\n"); close (s); xfree (ifc.ifc_buf); return false; } } res->clear (); bhash addrs; p = ifc.ifc_buf; e = p + ifc.ifc_len; while (p < e) { struct ifreq *ifrp = (struct ifreq *) p; struct ifreq ifr = *ifrp; #ifndef HAVE_SA_LEN p += sizeof (ifr); #else /* !HAVE_SA_LEN */ p += sizeof (ifrp->ifr_name) + max (sizeof (ifrp->ifr_addr), (size_t) ifrp->ifr_addr.sa_len); #endif /* !HAVE_SA_LEN */ if (ifrp->ifr_addr.sa_family != AF_INET) continue; if (ioctl (s, SIOCGIFFLAGS, &ifr) < 0) { warn ("SIOCGIFFLAGS (%.*s): %m\n", (int) sizeof (ifr.ifr_name), ifr.ifr_name); continue; } in_addr a = ((struct sockaddr_in *) &ifrp->ifr_addr)->sin_addr; if ((ifr.ifr_flags & IFF_UP) && !addrs[a]) { addrs.insert (a); res->push_back (a); } } xfree (ifc.ifc_buf); close (s); return true; } avenger-0.8.5/libasync/.gitignore0000644000175000017500000000002611221235216013661 00000000000000chartables.c dftables avenger-0.8.5/libasync/rwfd.h0000644000175000017500000000053311221235746013017 00000000000000#ifdef __cplusplus extern "C" { #endif ssize_t readvfd (int fd, const struct iovec *iov, int iovcnt, int *rfdp); ssize_t writevfd (int fd, const struct iovec *iov, int iovcnt, int wfd); ssize_t readfd (int fd, void *buf, size_t len, int *rfdp); ssize_t writefd (int fd, const void *buf, size_t len, int wfd); #ifdef __cplusplus } #endif avenger-0.8.5/libasync/myname.C0000644000175000017500000000406711221237220013271 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "dns.h" str mydomain () { if (!(_res.options & RES_INIT)) res_init (); return _res.dnsrch[0]; } #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 256 #endif /* !MAXHOSTNAMELEN */ str myname () { char namebuf[MAXHOSTNAMELEN+1]; namebuf[MAXHOSTNAMELEN] = '\0'; if (gethostname (namebuf, MAXHOSTNAMELEN) < 0) panic ("gethostname: %m\n"); if (strchr (namebuf, '.')) return namebuf; if (!(_res.options & RES_INIT)) res_init (); if (_res.dnsrch[0] && _res.dnsrch[0][0]) return strbuf ("%s.%s", namebuf, _res.dnsrch[0]); if (hostent *hp = gethostbyname (namebuf)) { if (strchr (hp->h_name, '.')) return hp->h_name; else for (char **np = hp->h_aliases; *np; np++) if (strchr (*np, '.')) return *np; } vec av; if (myipaddrs (&av)) for (in_addr *ap = av.base (); ap < av.lim (); ap++) if (ap->s_addr != htonl (INADDR_LOOPBACK)) if (hostent *hp = gethostbyaddr ((char *) ap, sizeof (*ap), AF_INET)) { if (strchr (hp->h_name, '.')) return hp->h_name; else for (char **np = hp->h_aliases; *np; np++) if (strchr (*np, '.')) return *np; } warn ("cannot find fully qualified domain name of this host\n"); warn ("set system name to fully-qualified domain name " "or fix /etc/resolv.conf\n"); return NULL; } avenger-0.8.5/libasync/Makefile.am0000644000175000017500000000364412260422177013746 00000000000000## Process this file with automake to produce Makefile.in # $Id$ # Note: The files # internal.h pcre.h dftables.c maketables.c pcre.c study.c # are from pcre-4.5, the perl compatible regular expression library. # Pcre was written by Philip Hazel, and is distributed from # http://www.pcre.org/ # ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ noinst_LIBRARIES = libasync.a noinst_PROGRAMS = dftables libasync_a_SOURCES = \ arandom.c clock_gettime.c getopt_long.c maketables.c pcre.c rwfd.c stktrace.c study.c suidprotect.c \ aerr.C aios.C arena.C armor.C cbuf.C convertint.C core.C daemonize.C dns.C dnsparse.C err.C ident.C ifchg.C ihash.C itree.C malloc.C msb.C myaddrs.C myname.C parseopt.C pipe2str.C refcnt.C resolvconf.C rxx.C socket.C spawn.C str.C str2file.C straux.C suio++.C suio_vuprintf.C tcpconnect.C noinst_HEADERS = \ aios.h amisc.h arena.h array.h async.h autoconf.h backoff.h bitvec.h callback.h cbuf.h dns.h dnsimpl.h dnsparse.h err.h fdlim.h getopt_long.h ihash.h init.h internal.h itree.h keyfunc.h list.h msb.h opnew.h parseopt.h pcre.h qhash.h refcnt.h rwfd.h rxx.h serial.h stllike.h str.h suio++.h sysconf.h union.h vatmpl.h vec.h dftables_SOURCES = dftables.c dftables_LDADD = pcre.o pcre.lo: chartables.c chartables.c: dftables ./dftables $@ DEPEND_ON_MAKEFILE = daemonize.o daemonize.lo spawn.o spawn.lo $(DEPEND_ON_MAKEFILE): Makefile stktrace.o: $(srcdir)/stktrace.c $(srcdir)/sysconf.h $(COMPILE) $(NW) -c $(srcdir)/stktrace.c EXTRA_DIST = .gitignore CLEANFILES = core *.core *~ *.rpo dftables chartables.c stamp-async-repo MAINTAINERCLEANFILES = Makefile.in # This assumes sfs1 is a symlink to the SFS sources .PHONY: getsrc getsrc: @set -ex; \ for file in $(libasync_a_SOURCES) $(noinst_HEADERS); do \ case $$file in \ autoconf.h|chartables.c|getopt_long.*) \ ;; \ *) \ cp $(srcdir)/sfs1/async/$$file $(srcdir)/ \ ;; \ esac; \ done avenger-0.8.5/libasync/getopt_long.c0000644000175000017500000003626011221235216014367 00000000000000/* $Id$ */ /* * Copyright (c) 2002 Todd C. Miller * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Sponsored in part by the Defense Advanced Research Projects * Agency (DARPA) and Air Force Research Laboratory, Air Force * Materiel Command, USAF, under agreement number F39502-99-1-0512. */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include "getopt_long.h" #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ #ifdef REPLACE_GETOPT int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = '?'; /* character checked for validity */ int optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #endif #define PRINT_ERROR ((opterr) && (*options != ':')) #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ /* return values */ #define BADCH (int)'?' #define BADARG ((*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 #define EMSG "" static int getopt_internal (int, char *const *, const char *, const struct option *, int *, int); static int parse_long_options (char *const *, const char *, const struct option *, int *, int); static int gcd (int, int); static void permute_args (int, int, int, char *const *); static char *place = EMSG; /* option letter processing */ /* XXX: set optreset to 1 rather than these two */ static int nonopt_start = -1; /* first non option argument (for permute) */ static int nonopt_end = -1; /* first option after non options (for permute) */ /* Error messages */ static const char recargchar[] = "option requires an argument -- %c\n"; static const char recargstring[] = "option requires an argument -- %s\n"; static const char ambig[] = "ambiguous option -- %.*s\n"; static const char noarg[] = "option doesn't take an argument -- %.*s\n"; static const char illoptchar[] = "unknown option -- %c\n"; static const char illoptstring[] = "unknown option -- %s\n"; /* * Compute the greatest common divisor of a and b. */ static int gcd (int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return (b); } /* * Exchange the block from nonopt_start to nonopt_end with the block * from nonopt_end to opt_end (keeping the same order of arguments * in each block). */ static void permute_args (int panonopt_start, int panonopt_end, int opt_end, char *const *nargv) { int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; /* * compute lengths of blocks and number and size of cycles */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd (nnonopts, nopts); cyclelen = (opt_end - panonopt_start) / ncycle; for (i = 0; i < ncycle; i++) { cstart = panonopt_end + i; pos = cstart; for (j = 0; j < cyclelen; j++) { if (pos >= panonopt_end) pos -= nnonopts; else pos += nopts; swap = nargv[pos]; /* LINTED const cast */ ((char **) nargv)[pos] = nargv[cstart]; /* LINTED const cast */ ((char **) nargv)[cstart] = swap; } } } /* * parse_long_options -- * Parse long options in argc/argv argument vector. * Returns -1 if short_too is set and the option does not match long_options. */ static int parse_long_options (char *const *nargv, const char *options, const struct option *long_options, int *idx, int short_too) { char *current_argv, *has_equal; size_t current_argv_len; int i, match; current_argv = place; match = -1; optind++; if ((has_equal = strchr (current_argv, '=')) != NULL) { /* argument found (--option=arg) */ current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen (current_argv); for (i = 0; long_options[i].name; i++) { /* find matching long option */ if (strncmp (current_argv, long_options[i].name, current_argv_len)) continue; if (strlen (long_options[i].name) == current_argv_len) { /* exact match */ match = i; break; } /* * If this is a known short option, don't allow * a partial match of a single character. */ if (short_too && current_argv_len == 1) continue; if (match == -1) /* partial match */ match = i; else { /* ambiguous abbreviation */ if (PRINT_ERROR) fprintf (stderr, ambig, (int) current_argv_len, current_argv); optopt = 0; return (BADCH); } } if (match != -1) { /* option found */ if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) fprintf (stderr, noarg, (int) current_argv_len, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; return (BADARG); } if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use next nargv */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' indicates no error * should be generated. */ if (PRINT_ERROR) fprintf (stderr, recargstring, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; --optind; return (BADARG); } } else { /* unknown option */ if (short_too) { --optind; return (-1); } if (PRINT_ERROR) fprintf (stderr, illoptstring, current_argv); optopt = 0; return (BADCH); } if (idx) *idx = match; if (long_options[match].flag) { *long_options[match].flag = long_options[match].val; return (0); } else return (long_options[match].val); } /* * getopt_internal -- * Parse argc/argv argument vector. Called by user level routines. */ static int getopt_internal (int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx, int flags) { char *oli; /* option letter list index */ int optchar, short_too; static int posixly_correct = -1; if (options == NULL) return (-1); /* * Disable GNU extensions if POSIXLY_CORRECT is set or options * string begins with a '+'. */ if (posixly_correct == -1) posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL); if (posixly_correct || *options == '+') flags &= ~FLAG_PERMUTE; else if (*options == '-') flags |= FLAG_ALLARGS; if (*options == '+' || *options == '-') options++; /* * XXX Some GNU programs (like cvs) set optind to 0 instead of * XXX using optreset. Work around this braindamage. */ if (optind == 0) optind = optreset = 1; optarg = NULL; if (optreset) nonopt_start = nonopt_end = -1; start: if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc) { /* end of argument vector */ place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ permute_args (nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* * If we skipped non-options, set optind * to the first of them. */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr (options, '-') == NULL)) { place = EMSG; /* found non-option */ if (flags & FLAG_ALLARGS) { /* * GNU extension: * return non-option as argument to option 1 */ optarg = nargv[optind++]; return (INORDER); } if (!(flags & FLAG_PERMUTE)) { /* * If no permutation wanted, stop parsing * at first non-option. */ return (-1); } /* do permutation */ if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { permute_args (nonopt_start, nonopt_end, optind, nargv); nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; /* process next argument */ goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; /* * If we have "-" do nothing, if "--" we are done. */ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; /* * We found an option (--), so if we skipped * non-options, we have to permute. */ if (nonopt_end != -1) { permute_args (nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } } /* * Check long options if: * 1) we were passed some * 2) the arg is not just "-" * 3) either the arg starts with -- we are getopt_long_only() */ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { short_too = 0; if (*place == '-') place++; /* --foo long option */ else if (*place != ':' && strchr (options, *place) != NULL) short_too = 1; /* could be short option too */ optchar = parse_long_options (nargv, options, long_options, idx, short_too); if (optchar != -1) { place = EMSG; return (optchar); } } if ((optchar = (int) *place++) == (int) ':' || (optchar == (int) '-' && *place != '\0') || (oli = strchr (options, optchar)) == NULL) { /* * If the user specified "-" and '-' isn't listed in * options, return -1 (non-option) as per POSIX. * Otherwise, it is an unknown option character (or ':'). */ if (optchar == (int) '-' && *place == '\0') return (-1); if (!*place) ++optind; if (PRINT_ERROR) fprintf (stderr, illoptchar, optchar); optopt = optchar; return (BADCH); } if (long_options != NULL && optchar == 'W' && oli[1] == ';') { /* -W long-option */ if (*place) /* no space */ /* NOTHING */ ; else if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) fprintf (stderr, recargchar, optchar); optopt = optchar; return (BADARG); } else /* white space */ place = nargv[optind]; optchar = parse_long_options (nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } if (*++oli != ':') { /* doesn't take argument */ if (!*place) ++optind; } else { /* takes (optional) argument */ optarg = NULL; if (*place) /* no white space */ optarg = place; /* XXX: disable test for :: if PC? (GNU doesn't) */ else if (oli[1] != ':') { /* arg not optional */ if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) fprintf (stderr, recargchar, optchar); optopt = optchar; return (BADARG); } else optarg = nargv[optind]; } else if (!(flags & FLAG_PERMUTE)) { /* * If permutation is disabled, we can accept an * optional arg separated by whitespace. */ if (optind + 1 < nargc) optarg = nargv[++optind]; } place = EMSG; ++optind; } /* dump back option letter */ return (optchar); } #ifdef REPLACE_GETOPT /* * getopt -- * Parse argc/argv argument vector. * * [eventually this will replace the BSD getopt] */ int getopt (int nargc, char *const *nargv, const char *options) { /* * We dont' pass FLAG_PERMUTE to getopt_internal() since * the BSD getopt(3) (unlike GNU) has never done this. * * Furthermore, since many privileged programs call getopt() * before dropping privileges it makes sense to keep things * as simple (and bug-free) as possible. */ return (getopt_internal (nargc, nargv, options, NULL, NULL, 0)); } #endif /* REPLACE_GETOPT */ /* * getopt_long -- * Parse argc/argv argument vector. */ int getopt_long (int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal (nargc, nargv, options, long_options, idx, FLAG_PERMUTE)); } /* * getopt_long_only -- * Parse argc/argv argument vector. */ int getopt_long_only (int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal (nargc, nargv, options, long_options, idx, FLAG_PERMUTE | FLAG_LONGONLY)); } avenger-0.8.5/libasync/str2file.C0000644000175000017500000000612611332761414013545 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "amisc.h" int mktmp_atomic (str tmpfile, int perm) { int fd; struct stat sb1, sb2; for (;;) { for (;;) { if ((fd = open (tmpfile, O_CREAT|O_EXCL|O_WRONLY, perm)) >= 0 || errno != EEXIST) return fd; if (lstat (tmpfile, &sb1) >= 0) { if (!S_ISREG (sb1.st_mode)) { errno = EEXIST; return -1; } break; } if (errno != ENOENT) return -1; } for (;;) { if ((fd = open (tmpfile, O_CREAT|O_EXCL|O_WRONLY, perm)) >= 0 || errno != EEXIST) return fd; sleep (1); if (lstat (tmpfile, &sb2) < 0) { if (errno != ENOENT) return -1; continue; } if (!S_ISREG (sb2.st_mode)) { errno = EEXIST; return -1; } if (sb1.st_dev != sb2.st_dev || sb1.st_ino != sb2.st_ino || sb1.st_size != sb2.st_size) sb1 = sb2; else if (unlink (tmpfile) >= 0) { sleep (1); break; } } } } bool str2file (str file, str s, int perm, bool excl, struct stat *sbp) { if (!file.len () || file.len () < strlen (file)) { errno = EINVAL; return false; } if (file[file.len () - 1] == '/') { errno = EISDIR; return false; } str tmpfile = file << "~"; unlink (tmpfile); int fd; if (excl) fd = open (tmpfile, O_CREAT|O_EXCL|O_WRONLY, perm); else fd = mktmp_atomic (tmpfile, perm); if (fd < 0) return false; if (write (fd, s.cstr (), s.len ()) != int (s.len ())) { close (fd); unlink (tmpfile); return false; } int err = 0; if (s.len () && s[s.len () - 1] != '\n') err = write (fd, "\n", 1); if (!err) err = fsync (fd); if (sbp && !err) err = fstat (fd, sbp); if (close (fd) < 0 || err < 0 || (excl && link (tmpfile, file) < 0) || (!excl && rename (tmpfile, file) < 0)) { unlink (tmpfile); return false; } if (excl) unlink (tmpfile); return true; } str file2str (str file) { int fd = open (file, O_RDONLY, 0); if (fd < 0) return NULL; struct stat sb; if (fstat (fd, &sb) < 0) { close (fd); return NULL; } if (!S_ISREG (sb.st_mode)) { warn << file << ": not a regular file\n"; close (fd); errno = EINVAL; return NULL; } mstr m (sb.st_size); errno = EAGAIN; ssize_t n = read (fd, m, sb.st_size); int saved_errno = errno; close (fd); errno = saved_errno; if (n < 0) return NULL; m.setlen (n); return m; } avenger-0.8.5/libasync/core.C0000644000175000017500000003071211332761414012741 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "async.h" #include "fdlim.h" #include "ihash.h" #include "itree.h" #include "list.h" #include #define FD_SETSIZE_ROUND (sizeof (long))/* # Bytes to which to round fd_sets */ int fd_set_bytes; // Size in bytes of a [wide] fd_set int maxfd; bool amain_panic; static int nselfd; timespec tsnow; const time_t &timenow = tsnow.tv_sec; static timeval selwait; #ifdef WRAP_DEBUG #define CBTR_FD 0x0001 #define CBTR_TIME 0x0002 #define CBTR_SIG 0x0004 #define CBTR_CHLD 0x0008 #define CBTR_LAZY 0x0010 static int callback_trace; static bool callback_time; static inline const char * timestring () { if (!callback_time) return ""; clock_gettime (CLOCK_REALTIME, &tsnow); static str buf; buf = strbuf ("%d.%06d ", int (tsnow.tv_sec), int (tsnow.tv_nsec/1000)); return buf; } #endif /* WRAP_DEBUG */ struct child { pid_t pid; cbi cb; ihash_entry link; child (pid_t p, cbi c) : pid (p), cb (c) {} }; static ihash chldcbs; static time_t chldcb_check_last; struct timecb_t { timespec ts; const cbv cb; itree_entry link; timecb_t (const timespec &t, const cbv &c) : ts (t), cb (c) {} }; static itree timecbs; static bool timecbs_altered; struct lazycb_t { const time_t interval; time_t next; const cbv cb; list_entry link; lazycb_t (time_t interval, cbv cb); ~lazycb_t (); }; static bool lazycb_removed; static list *lazylist; const int fdsn = 2; static cbv::ptr *fdcbs[fdsn]; static fd_set *fdsp[fdsn]; static fd_set *fdspt[fdsn]; static int sigpipes[2] = { -1, -1 }; #ifdef NSIG const int nsig = NSIG; #else /* !NSIG */ const int nsig = 32; #endif /* !NSIG */ /* Note: sigdocheck and sigcaught intentionally ints rather than * bools. The hope is that an int can safely be written without * affecting surrounding memory. (This is certainly not the case on * some architectures if bool is a char. Consider getting signal 2 * right after signal 3 on an alpha, for instance. You might end up * clearing sigcaught[2] when you finish setting sigcaught[3].) */ static volatile int sigdocheck; static volatile int sigcaught[nsig]; static bssptr sighandler[nsig]; static void sigcb_check (); void chldcb (pid_t pid, cbi::ptr cb) { if (child *c = chldcbs[pid]) { chldcbs.remove (c); delete c; } if (cb) chldcbs.insert (New child (pid, cb)); } void chldcb_check () { for (;;) { int status; pid_t pid = waitpid (-1, &status, WNOHANG); if (pid == 0 || pid == -1) break; if (child *c = chldcbs[pid]) { chldcbs.remove (c); #ifdef WRAP_DEBUG if (callback_trace & CBTR_CHLD) warn ("CALLBACK_TRACE: %schild pid %d (status %d) %s <- %s\n", timestring (), pid, status, c->cb->dest, c->cb->line); #endif /* WRAP_DEBUG */ (*c->cb) (status); delete c; } } chldcb_check_last = timenow; } timecb_t * timecb (const timespec &ts, cbv cb) { timecb_t *to = New timecb_t (ts, cb); timecbs.insert (to); // timecbs_altered = true; return to; } timecb_t * delaycb (time_t sec, u_int32_t nsec, cbv cb) { timespec ts; clock_gettime (CLOCK_REALTIME, &ts); ts.tv_sec += sec; ts.tv_nsec += nsec; if (ts.tv_nsec >= 1000000000) { ts.tv_nsec -= 1000000000; ts.tv_sec++; } return timecb (ts, cb); } void timecb_remove (timecb_t *to) { if (!to) return; for (timecb_t *tp = timecbs[to->ts]; tp != to; tp = timecbs.next (tp)) if (!tp || tp->ts != to->ts) panic ("timecb_remove: invalid timecb_t\n"); timecbs_altered = true; timecbs.remove (to); delete to; } void timecb_check () { clock_gettime (CLOCK_REALTIME, &tsnow); timecb_t *tp, *ntp; for (tp = timecbs.first (); tp && tp->ts <= tsnow; tp = timecbs_altered ? timecbs.first () : ntp) { ntp = timecbs.next (tp); timecbs.remove (tp); timecbs_altered = false; #ifdef WRAP_DEBUG if (callback_trace & CBTR_TIME) warn ("CALLBACK_TRACE: %stimecb %s <- %s\n", timestring (), tp->cb->dest, tp->cb->line); #endif /* WRAP_DEBUG */ (*tp->cb) (); delete tp; } selwait.tv_usec = 0; if (!(tp = timecbs.first ())) selwait.tv_sec = 86400; else { clock_gettime (CLOCK_REALTIME, &tsnow); if (tp->ts < tsnow) selwait.tv_sec = 0; else if (tp->ts.tv_nsec >= tsnow.tv_nsec) { selwait.tv_sec = tp->ts.tv_sec - tsnow.tv_sec; selwait.tv_usec = (tp->ts.tv_nsec - tsnow.tv_nsec) / 1000; } else { selwait.tv_sec = tp->ts.tv_sec - tsnow.tv_sec - 1; selwait.tv_usec = (1000000000 + tp->ts.tv_nsec - tsnow.tv_nsec) / 1000; } } if (sigdocheck) selwait.tv_sec = selwait.tv_usec = 0; } void fdcb (int fd, selop op, cbv::ptr cb) { assert (fd >= 0); assert (fd < maxfd); fdcbs[op][fd] = cb; if (cb) { if (fd >= nselfd) nselfd = fd + 1; FD_SET (fd, fdsp[op]); } else FD_CLR (fd, fdsp[op]); } static void fdcb_check (void) { for (int i = 0; i < fdsn; i++) memcpy (fdspt[i], fdsp[i], fd_set_bytes); int n = select (nselfd, fdspt[0], fdspt[1], NULL, &selwait); if (n < 0 && errno != EINTR) panic ("select: %m\n"); clock_gettime (CLOCK_REALTIME, &tsnow); if (sigdocheck) sigcb_check (); for (int fd = 0; fd < maxfd && n > 0; fd++) for (int i = 0; i < fdsn; i++) if (FD_ISSET (fd, fdspt[i])) { n--; if (FD_ISSET (fd, fdsp[i])) { #ifdef WRAP_DEBUG if (fd != errfd && fd != sigpipes[0] && (callback_trace & CBTR_FD)) warn ("CALLBACK_TRACE: %sfdcb %d%c %s <- %s\n", timestring (), fd, "rwe"[i], fdcbs[i][fd]->dest, fdcbs[i][fd]->line); #endif /* WRAP_DEBUG */ (*fdcbs[i][fd]) (); } } } static void sigcatch (int sig) { sigdocheck = 1; sigcaught[sig] = 1; selwait.tv_sec = selwait.tv_usec = 0; /* On some operating systems, select is not a system call but is * implemented inside libc. This may cause a race condition in * which select ends up being called with the original (non-zero) * value of selwait. We avoid the problem by writing to a pipe that * will wake up the select. */ use (write (sigpipes[1], "", 1)); } cbv::ptr sigcb (int sig, cbv::ptr cb, int flags) { sigset_t set; if (!sigemptyset (&set) && !sigaddset (&set, sig)) sigprocmask (SIG_UNBLOCK, &set, NULL); struct sigaction sa; assert (sig > 0 && sig < nsig); bzero (&sa, sizeof (sa)); sa.sa_handler = cb ? sigcatch : SIG_DFL; sa.sa_flags = flags; if (sigaction (sig, &sa, NULL) < 0) // Must be bad signal, serious bug panic ("sigcb: sigaction: %m\n"); cbv::ptr ocb = sighandler[sig]; sighandler[sig] = cb; return ocb; } static void sigcb_check () { if (sigdocheck) { char buf[64]; while (read (sigpipes[0], buf, sizeof (buf)) > 0) ; sigdocheck = 0; for (int i = 1; i < nsig; i++) if (sigcaught[i]) { sigcaught[i] = 0; if (cbv::ptr cb = sighandler[i]) { #ifdef WRAP_DEBUG if ((callback_trace & CBTR_SIG) && i != SIGCHLD) { # ifdef NEED_SYS_SIGNAME_DECL warn ("CALLBACK_TRACE: %ssignal %d %s <- %s\n", timestring (), i, cb->dest, cb->line); # else /* !NEED_SYS_SIGNAME_DECL */ warn ("CALLBACK_TRACE: %sSIG%s %s <- %s\n", timestring (), sys_signame[i], cb->dest, cb->line); # endif /* !NEED_SYS_SIGNAME_DECL */ } #endif /* WRAP_DEBUG */ (*cb) (); } } } } lazycb_t::lazycb_t (time_t i, cbv c) : interval (i), next (timenow + interval), cb (c) { lazylist->insert_head (this); } lazycb_t::~lazycb_t () { lazylist->remove (this); } lazycb_t * lazycb (time_t interval, cbv cb) { return New lazycb_t (interval, cb); } void lazycb_remove (lazycb_t *lazy) { lazycb_removed = true; delete lazy; } void lazycb_check () { clock_gettime (CLOCK_REALTIME, &tsnow); restart: lazycb_removed = false; for (lazycb_t *lazy = lazylist->first; lazy; lazy = lazylist->next (lazy)) { if (timenow < lazy->next) continue; lazy->next = timenow + lazy->interval; #ifdef WRAP_DEBUG if (callback_trace & CBTR_LAZY) warn ("CALLBACK_TRACE: %slazy %s <- %s\n", timestring (), lazy->cb->dest, lazy->cb->line); #endif /* WRAP_DEBUG */ (*lazy->cb) (); if (lazycb_removed) goto restart; } } static void ainit () { if (sigpipes[0] == -1) { if (pipe (sigpipes) < 0) fatal ("could not create sigpipes: %m\n"); _make_async (sigpipes[0]); _make_async (sigpipes[1]); close_on_exec (sigpipes[0]); close_on_exec (sigpipes[1]); fdcb (sigpipes[0], selread, cbv_null); /* Set SA_RESTART for SIGCHLD, primarily for the benefit of * stdio-using code like lex/flex scanners. These tend to flip out * if read ever returns EINTR. */ sigcb (SIGCHLD, wrap (chldcb_check), (SA_NOCLDSTOP #ifdef SA_RESTART | SA_RESTART #endif /* SA_RESTART */ )); sigcatch (SIGCHLD); } } static inline void _acheck () { if (amain_panic) panic ("child process returned from afork ()\n"); lazycb_check (); fdcb_check (); sigcb_check (); #if 0 /* * On planet-lab's weird Linux kernel, sometimes processes stop * receiving SIGCHLD signals. To avoid endlessly accumulating * Zombie children, we periodically try to reap children anyway, * even when we haven't received a SIGCHLD. This is kind of gross, * but without the workaround one can end up completely filling the * process table with zombies (making it hard to log in and fix the * problem). */ if (timenow > chldcb_check_last + 60) chldcb_check (); #endif timecb_check (); } void acheck () { timecb_check (); ainit (); _acheck (); } void amain () { static bool amain_called; if (amain_called) panic ("amain called recursively\n"); amain_called = true; ainit (); err_init (); timecb_check (); for (;;) _acheck (); } int async_init::count; void async_init::start () { static bool initialized; if (initialized) panic ("async_init called twice\n"); initialized = true; /* Ignore SIGPIPE, since we may get a lot of these */ struct sigaction sa; bzero (&sa, sizeof (sa)); sa.sa_handler = SIG_IGN; sigaction (SIGPIPE, &sa, NULL); if (!execsafe ()) { int fdlim_hard = fdlim_get (1); if (char *p = getenv ("FDLIM_HARD")) { int n = atoi (p); if (n > 0 && n < fdlim_hard) { fdlim_hard = n; fdlim_set (fdlim_hard, -1); } } } if (!getenv ("FDLIM_HARD") || !execsafe ()) { str var = strbuf ("FDLIM_HARD=%d", fdlim_get (1)); xputenv (const_cast (var.cstr())); var = strbuf ("FDLIM_SOFT=%d", fdlim_get (0)); xputenv (const_cast (var.cstr())); } #ifndef HAVE_WIDE_SELECT fdlim_set (FD_SETSIZE, execsafe ()); maxfd = fdlim_get (0); fd_set_bytes = sizeof (fd_set); #else /* HAVE_WIDE_SELECT */ if (!execsafe () || fdlim_set (FDLIM_MAX, 1) < 0) fdlim_set (fdlim_get (1), 0); maxfd = fdlim_get (0); fd_set_bytes = (maxfd+7)/8; if (fd_set_bytes % FD_SETSIZE_ROUND) fd_set_bytes += FD_SETSIZE_ROUND - (fd_set_bytes % FD_SETSIZE_ROUND); #endif /* HAVE_WIDE_SELECT */ for (int i = 0; i < fdsn; i++) { fdcbs[i] = New cbv::ptr[maxfd]; fdsp[i] = (fd_set *) xmalloc (fd_set_bytes); bzero (fdsp[i], fd_set_bytes); fdspt[i] = (fd_set *) xmalloc (fd_set_bytes); bzero (fdspt[i], fd_set_bytes); } lazylist = New list; #ifdef WRAP_DEBUG if (char *p = getenv ("CALLBACK_TRACE")) { if (strchr (p, 'f')) callback_trace |= CBTR_FD; if (strchr (p, 't')) callback_trace |= CBTR_TIME; if (strchr (p, 's')) callback_trace |= CBTR_SIG; if (strchr (p, 'c')) callback_trace |= CBTR_CHLD; if (strchr (p, 'l')) callback_trace |= CBTR_LAZY; if (strchr (p, 'a')) callback_trace |= -1; if (strchr (p, 'T')) callback_time = true; } #endif /* WRAP_DEBUG */ } void async_init::stop () { err_flush (); } avenger-0.8.5/libasync/bitvec.h0000644000175000017500000001116511221237220013321 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ /* XXX - this is suboptimal */ #ifndef _ASYNC_BITVEC_H_ #define _ASYNC_BITVEC_H_ 1 #include "str.h" class bitvec { protected: friend void swap (bitvec &a, bitvec &b); typedef unsigned long map_t; enum { mapbits = 8 * sizeof (map_t) }; map_t *map; size_t nbits; void init () { map = NULL; nbits = 0; } static size_t nbytes (size_t nb) { return ((nb + mapbits - 1) / mapbits) * sizeof (map_t); } void datalloc (size_t nb) { if (nb) map = static_cast (xrealloc (map, nbytes (nb))); else { /* Jump through hoops for dmalloc */ xfree (map); map = NULL; } } #ifdef CHECK_BOUNDS #define bcheck(n) assert ((size_t) (n) < nbits) #define rcheck(s, e) assert (s <= e && e <= nbits) #else /* !CHECK_BOUNDS */ #define bcheck(n) #define rcheck(s, e) #endif /* !CHECK_BOUNDS */ class wbit { friend class bitvec; map_t *const intp; const u_int bitpos; wbit (map_t *i, u_int b) : intp (i), bitpos (b) {} public: operator bool () const { return *intp & map_t (1) << bitpos; } wbit &operator= (bool v) { if (v) *intp |= map_t (1) << bitpos; else *intp &= ~(map_t (1) << bitpos); return *this; } wbit &operator^= (bool v) { *intp ^= map_t (v) << bitpos; return *this; } }; void range_set (size_t s, size_t e) { size_t sp = s / mapbits, ep = e / mapbits; int sb = s % mapbits, eb = e % mapbits; if (sp == ep) { if (eb) map[sp] |= (map_t (-1) << sb) & ~(map_t (-1) << eb); } else { map[sp] |= (map_t (-1) << sb); if (eb) map[ep] |= ~(map_t (-1) << eb); memset (&map[sp+1], 0xff, (ep - sp - 1) * sizeof (map_t)); } } void range_clr (size_t s, size_t e) { size_t sp = s / mapbits, ep = e / mapbits; int sb = s % mapbits, eb = e % mapbits; if (sp == ep) { if (eb) map[sp] &= ~(map_t (-1) << sb) | (map_t (-1) << eb); } else { map[sp] &= ~(map_t (-1) << sb); if (eb) map[ep] &= (map_t (-1) << eb); bzero (&map[sp+1], (ep - sp - 1) * sizeof (map_t)); } } public: bitvec () { init (); } bitvec (size_t n) { init (); zsetsize (n); } bitvec (const bitvec &v) { init (); *this = v; } ~bitvec () { xfree (map); } void setsize (size_t n) { datalloc (nbits = n); } void zsetsize (size_t n) { datalloc (n); if (n > nbits) range_clr (nbits, n); nbits = n; } void osetsize (size_t n) { datalloc (n); if (n > nbits) range_set (nbits, n); nbits = n; } size_t size () const { return nbits; } bool at (ptrdiff_t i) const { bcheck (i); return map[(size_t) i / mapbits] & map_t (1) << ((size_t) i % mapbits); } void (setbit) (ptrdiff_t i, bool val) { bcheck (i); if (val) map[(size_t) i / mapbits] |= map_t (1) << ((size_t) i % mapbits); else map[(size_t) i / mapbits] &= ~(map_t (1) << ((size_t) i % mapbits)); } void setrange (size_t s, size_t e, bool v) { rcheck (s, e); if (v) range_set (s, e); else range_clr (s, e); } bool operator[] (ptrdiff_t i) const { bcheck (i); return map[(size_t) i / mapbits] & map_t (1) << ((size_t) i % mapbits); } wbit operator[] (ptrdiff_t i) { bcheck (i); return wbit (map + (size_t) i / mapbits, (size_t) i % mapbits); } bitvec &operator= (const bitvec &v) { setsize (v.nbits); memcpy (map, v.map, nbytes (nbits)); return *this; } #undef bcheck #undef rcheck }; inline void swap (bitvec &a, bitvec &b) { bitvec::map_t *map = a.map; a.map = b.map; b.map = map; size_t nbits = a.nbits; a.nbits = b.nbits; b.nbits = nbits; } inline const strbuf & strbuf_cat (const strbuf &sb, const bitvec &v) { char *p = sb.tosuio ()->getspace (v.size ()); for (size_t i = 0; i < v.size (); i++) p[i] = v[i] ? '1' : '0'; sb.tosuio ()->print (p, v.size ()); return sb; } #endif /* !_ASYNC_BITVEC_H_ */ avenger-0.8.5/libasync/rxx.h0000644000175000017500000001064611221237220012671 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _RXX_H_ #define _RXX_H_ 1 #include "sysconf.h" extern "C" { #include "pcre.h" } #include "str.h" #include "init.h" INIT (rxxinit); extern "C" void *rcmalloc (size_t n); extern "C" void rcfree (void *p); extern "C" void *rccopy (void *p); class rxx { protected: pcre *re; pcre_extra *extra; int nsubpat; int *ovector; int ovecsize; str subj; str init (const char *pat, const char *opt); void copy (const rxx &r) { re = static_cast (rccopy (r.re)); extra = static_cast (rccopy (r.extra)); nsubpat = 0; ovector = NULL; ovecsize = r.ovecsize; } rxx &operator= (const rxx &); void mknull () { re = NULL; extra = NULL; nsubpat = 0; ovector = NULL; ovecsize = NULL; subj = NULL; } rxx () {} void freemem () { rcfree (re); rcfree (extra); delete[] ovector; } public: void _exec (const char *p, size_t len, int options); void exec (str s, int options); class matchresult { const rxx &r; public: matchresult (const rxx &r) : r (r) {} operator bool () const { return r.success (); } operator str () const { return r.at (0); } str operator[] (ptrdiff_t n) const { return r.at (n); } }; rxx (const char *pat, const char *opt = "") { if (str s = init (pat, opt)) panic ("%s", s.cstr ()); } rxx (const rxx &r) { assert (r.re); copy (r); } ~rxx () { freemem (); } str study () { const char *err; extra = pcre_study (re, 0, &err); return err; } void clear () { nsubpat = 0; subj = NULL; } matchresult search (str s, int opt = 0) { exec (s, opt); return *this; } matchresult match (str s, int opt = 0) { exec (s, opt | PCRE_ANCHORED); if (nsubpat > 0 && implicit_cast (ovector[1]) != s.len ()) nsubpat = 0; return *this; } bool success () const { return nsubpat > 0; } str at (ptrdiff_t n) const; int start (int n) const { assert (n >= 0); return n < nsubpat ? ovector[2*n] : -1; } int end (int n) const { assert (n >= 0); return n < nsubpat ? ovector[2*n+1] : -1; } int len (int n) const { assert (n >= 0); size_t i = 2 * n; return n < nsubpat && ovector[i] >= 0 ? ovector[i+1] - ovector[i] : -1; } str operator[] (ptrdiff_t n) const { return at (n); } }; class rrxx : public rxx { str err; void mknull () { err = "uninitialized"; rxx::mknull (); } public: rrxx () { mknull (); } explicit rrxx (const char *pat, const char *opt = "") { err = init (pat, opt); } rrxx (const rxx &r) { err = NULL; copy (r); } rrxx (const rrxx &r) { err = r.err; copy (r); } bool compile (const char *pat, const char *opt = "") { freemem (); mknull (); err = init (pat, opt); return !err; } const str &geterr () const { return err; } }; inline rxx::matchresult operator/ (const str &s, rxx &r) { return r.search (s); } class strstrmatch { const str &s; const char *const p; protected: mutable const char *o; public: strstrmatch (const str &s, const char *p) : s (s), p (p), o ("") {} operator bool () const { rxx r (p, o); return r.search (s); } operator str () const { rxx r (p, o); return r.search (s)[0]; } str operator[] (ptrdiff_t n) const { rxx r (p, o); return r.search (s)[n]; } }; class strstroptmatch : public strstrmatch { public: strstroptmatch (const str &s, const char *p) : strstrmatch (s, p) {} const strstrmatch &operator/ (const char *opt) const { o = opt; return *this; } }; inline strstroptmatch operator/ (const str &s, const char *p) { return strstroptmatch (s, p); } int split (vec *out, rxx pat, str expr, size_t lim = (size_t) -1, bool emptylast = false); str join (str sep, const vec &v); #endif /* !_RXX_H_ */ avenger-0.8.5/libasync/arena.h0000644000175000017500000000361411221237220013133 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_ARENA_H_ #define _ASYNC_ARENA_H_ 1 #include "async.h" class arena { protected: enum { resv = sizeof (void *) }; u_int size; u_int avail; char *chunk; char *cur; void newchunk (size_t); public: arena () { size = avail = 0; chunk = cur = 0; } void *alloc (size_t bytes, size_t align = sizeof (double)) { int pad = (align - (chunk - (char *) 0)) % align; if (avail < pad + bytes) { newchunk (bytes + align); pad = (align - (chunk - (char *) 0)) % align; } void *ret = cur + pad; cur += bytes + pad; avail -= bytes + pad; return ret; } char *(strdup) (const char *str) { return strcpy ((char *) alloc (1 + strlen (str), 1), str); } #ifdef DMALLOC char *_strdup_leap (const char *, int, const char *str) { return strcpy ((char *) alloc (1 + strlen (str), 1), str); } char *dmalloc_strdup (const char *, int, const char *str, int) { return strcpy ((char *) alloc (1 + strlen (str), 1), str); } #endif /* DMALLOC */ ~arena (); }; inline void * operator new (size_t n, arena &a) { return a.alloc (n); } #endif /* !_ASYNC_ARENA_H_ */ avenger-0.8.5/libasync/cbuf.C0000644000175000017500000000476011221237220012722 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "cbuf.h" #include "stllike.h" void cbuf::resize (size_t n) { int nend = size (); char *nbuf = (char *) xmalloc (n); copyout (nbuf, nend); xfree (buf); buf = nbuf; buflen = n; empty = nend; start = 0; end = nend; } const iovec * cbuf::iniov () { inv[0].iov_base = buf + end; if (empty || start < end) { inv[0].iov_len = buflen - end; inv[1].iov_base = buf; inv[1].iov_len = start; } else { inv[0].iov_len = start - end; inv[1].iov_base = NULL; inv[1].iov_len = 0; } return inv; } void cbuf::addbytes (size_t n) { if (n) { assert (n <= space ()); empty = false; end += n; if (end >= buflen) end -= buflen; } } int cbuf::find (char c) { if (empty) return -1; if (start < end) { if (char *p = (char *) memchr (buf + start, c, end - start)) return p - (buf + start); return -1; } if (char *p = (char *) memchr (buf + start, c, buflen - start)) return p - (buf + start); if (char *p = (char *) memchr (buf, c, end)) return p - buf + buflen - start; return -1; }; const iovec * cbuf::outiov () { outv[0].iov_base = buf + start; if (start >= end && !empty) { outv[0].iov_len = buflen - start; outv[1].iov_base = buf; outv[1].iov_len = end; } else { outv[0].iov_len = end - start; outv[1].iov_base = NULL; outv[1].iov_len = 0; } return outv; } void cbuf::copyout (void *_dst, size_t len) { char *dst = static_cast (_dst); assert (len <= size ()); if (empty || start < end) memcpy (dst, buf + start, min (len, end - start)); else { size_t n = min (len, buflen - start); memcpy (dst, buf + start, n); if (len > n) memcpy (dst + n, buf, len - n); } rembytes (len); } avenger-0.8.5/libasync/serial.h0000644000175000017500000001027011221237220013320 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1999 David Mazieres (dm@uun.org) * * 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 _ASYNC_SERIAL_H_ #define _ASYNC_SERIAL_H_ 1 #include "str.h" bool str2file (str file, str s, int perm = 0666, bool excl = false, struct stat *sbp = NULL); str file2str (str file); static inline void putshort (void *_dp, u_int16_t val) { u_char *dp = static_cast (_dp); dp[0] = val >> 8; dp[1] = val; } static inline u_int16_t getshort (const void *_dp) { const u_char *dp = static_cast (_dp); return dp[0] << 8 | dp[1]; } static inline void putint (void *_dp, u_int32_t val) { u_char *dp = static_cast (_dp); dp[0] = val >> 24; dp[1] = val >> 16; dp[2] = val >> 8; dp[3] = val; } static inline u_int32_t getint (const void *_dp) { const u_char *dp = static_cast (_dp); return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3]; } static inline void puthyper (void *_dp, u_int64_t val) { u_char *dp = static_cast (_dp); dp[0] = val >> 56; dp[1] = val >> 48; dp[2] = val >> 40; dp[3] = val >> 32; dp[4] = val >> 24; dp[5] = val >> 16; dp[6] = val >> 8; dp[7] = val; } static inline u_int64_t gethyper (const void *_dp) { const u_char *dp = static_cast (_dp); return (u_int64_t) dp[0] << 56 | (u_int64_t) dp[1] << 48 | (u_int64_t) dp[2] << 40 | (u_int64_t) dp[3] << 32 | getint (dp + 4); } str armor64 (const void *, size_t); size_t armor64len (const u_char *); str dearmor64 (const char *, ssize_t len = -1); /* * RFC 1521 Base-64 encoding */ inline str armor64 (str bin) { return armor64 (bin.cstr (), bin.len ()); } inline str dearmor64 (str asc) { if (armor64len (reinterpret_cast (asc.cstr ())) != asc.len ()) return NULL; return dearmor64 (asc.cstr (), asc.len ()); } str armor32 (const void *, size_t); size_t armor32len (const u_char *s); str dearmor32 (const char *, ssize_t len = -1); /* * Alternate Base-64 encoding, suitable for file names. Uses '-' * instead of '/' and does not append any '=' chars. */ str armor64A (const void *s, size_t len); size_t armor64Alen (const u_char *s); str dearmor64A (const char *s, ssize_t len); inline str armor64A (str bin) { return armor64A (bin.cstr (), bin.len ()); } inline str dearmor64A (str asc) { if (armor64Alen (reinterpret_cast (asc.cstr ())) != asc.len ()) return NULL; return dearmor64A (asc.cstr (), asc.len ()); } /* * Base-32 encoding, using '2'-'9','a'-'k','m','n','p'-'z' * (i.e. digits and lower-case letters except 0,1,o,l). */ inline str armor32 (str bin) { return armor32 (bin.cstr (), bin.len ()); } inline str dearmor32 (str asc) { if (armor32len (reinterpret_cast (asc.cstr ())) != asc.len ()) return NULL; return dearmor32 (asc.cstr (), asc.len ()); } /* * Base-16 encoding */ inline bool hexconv (int &out, const char in) { if (in >= '0' && in <= '9') out = in - '0'; else if (in >= 'a' && in <= 'f') out = in - ('a' - 10); else if (in >= 'A' && in <= 'F') out = in - ('A' - 10); else return false; return true; } inline str hex2bytes (str asc) { if (asc.len () & 1) return NULL; mstr b (asc.len () / 2); int i = 0; for (const char *p = asc.cstr (), *e = p + asc.len (); p < e; p += 2) { int h, l; if (!hexconv (h, p[0]) || !hexconv (l, p[1])) return NULL; b[i++] = h << 4 | l; } return b; } // Note: see hexdump in str.h to print data in base-16 #endif /* !_ASYNC_SERIAL_H_ */ avenger-0.8.5/libasync/keyfunc.h0000644000175000017500000001101711221237220013505 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _KEYFUNC_H_ #define _KEYFUNC_H_ 1 template struct unref_t { typedef T base_type; typedef T unref_type; typedef const T &ref_type; typedef T &ncref_type; }; template struct unref_t { typedef T base_type; typedef const T unref_type; typedef const T &ref_type; typedef T &ncref_type; }; template struct unref_t { typedef T base_type; typedef T unref_type; typedef const T &ref_type; typedef T &ncref_type; }; template struct unref_t { typedef T base_type; typedef const T unref_type; typedef const T &ref_type; typedef T &ncref_type; }; #define CREF(T) unref_t::ref_type #define UNREF(T) unref_t::unref_type #define UNCREF(T) unref_t::base_type #define NCREF(T) unref_t::ncref_type #define HASHSEED 5381 inline u_int hash_bytes (const void *_key, int len, u_int seed = HASHSEED) { const u_char *key = (const u_char *) _key; const u_char *end; for (end = key + len; key < end; key++) seed = ((seed << 5) + seed) ^ *key; return seed; } inline u_int hash_string (const void *_p, u_int v = HASHSEED) { const char *p = (const char *) _p; while (*p) v = (33 * v) ^ (unsigned char) *p++; return v; } inline u_int hash_rotate (u_int val, u_int rot) { rot %= 8 * sizeof (val); return (val << rot) | (val >> (8 * sizeof (val) - rot)); } class hash_t { u_int val; public: hash_t () {} hash_t (u_int v) : val (v) {} operator u_int() const { return val; } }; template struct compare { compare () {} int operator() (typename CREF (T) a, typename CREF (T) b) const { return a < b ? -1 : b < a; } }; template struct compare : compare { compare () {} }; template struct equals { equals () {} bool operator() (typename CREF (T) a, typename CREF (T) b) const { return a == b; } }; template struct equals : equals { equals () {} }; template struct hashfn { hashfn () {} hash_t operator() (typename CREF (T) a) const { return a; } }; template struct hashfn : hashfn { hashfn () {} }; template struct hash2fn { hashfn h1; hashfn h2; hash2fn () {} hash_t operator() (typename CREF (T1) t1, typename CREF (T2) t2) const { return h1 (t1) ^ h2 (t2); } }; /* Don't compare pointers by accident */ template struct compare; template struct hashfn; /* Specializations for (char *) */ #define _CHAR_PTR(T, u) \ template<> \ struct compare { \ compare () {} \ int operator() (const u char *a, const u char *b) const \ { return strcmp ((char *) a, (char *) b); } \ }; \ template<> \ struct equals { \ equals () {} \ bool operator() (const u char *a, const u char *b) const \ { return !strcmp ((char *) a, (char *) b); } \ }; \ template<> \ struct hashfn { \ hashfn () {} \ hash_t operator() (const u char *a) const \ { return hash_string (a); } \ }; #define CHAR_PTR(T, u) _CHAR_PTR(T, u) _CHAR_PTR(T const, u) CHAR_PTR(char *,) CHAR_PTR(const char *,) CHAR_PTR(signed char *, signed) CHAR_PTR(const signed char *, signed) CHAR_PTR(unsigned char *, unsigned) CHAR_PTR(const unsigned char *, unsigned) template class keyfunc_1 { public: const F kf; keyfunc_1 () {} keyfunc_1 (const F &f) : kf (f) {} R operator() (typename CREF (V) a) const { return kf (a.*key); } }; template class keyfunc_2 { public: const F kf; keyfunc_2 () {} keyfunc_2 (const F &f) : kf (f) {} R operator() (typename CREF (V) a, typename CREF (V) b) const { return kf (a.*key, b.*key); } }; #endif /* !KEYFUNC_H_ */ avenger-0.8.5/libasync/suio++.h0000644000175000017500000001605711221237220013157 00000000000000// -*-c++-*- /* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _ASYNC_SUIOXX_H_ #define _ASYNC_SUIOXX_H_ 1 #include "opnew.h" #include "vec.h" #include "callback.h" class iovmgr { const iovec *iov; const iovec *lim; iovec cur; public: iovmgr (const iovec *iov, int iovcnt); void skip (size_t); size_t copyout (char *, size_t); size_t size () const; }; size_t iovsize (const iovec *, int); class suio { public: enum { smallbufsize = 0x80 }; enum { blocksize = 0x2000 }; private: typedef callback::ref cb_t; class uiocb { uiocb &operator= (const uiocb &); public: cb_t cb; u_int64_t nbytes; uiocb (u_int64_t nb, cb_t cb) : cb (cb), nbytes (nb) {} }; vec iovs; vec uiocbs; size_t uiobytes; u_int64_t nrembytes; u_int64_t nremiov; char *lastiovend; char *scratch_buf; char *scratch_pos; char *scratch_lim; suio (const suio &); suio &operator= (const suio &); protected: void *(*allocator) (size_t); void (*deallocator) (void *, size_t); char defbuf[smallbufsize]; static void *default_allocator (size_t n) { return txmalloc (n); } static void default_deallocator (void *p, size_t) { xfree (p); } void makeuiocbs (); char *morescratch (size_t); void pushiov (const void *base, size_t len); void slowcopy (const void *, size_t); void slowfill (char c, size_t n); void condemn_scratch (); public: suio (); ~suio (); void clear (); char *getspace (size_t n); char *getspace_aligned (size_t n); void fill (char c, ssize_t n); void copy (const void *, size_t); void copyv (const iovec *iov, size_t cnt, size_t skip = 0); void copyu (const suio *uio) { copyv (uio->iov (), uio->iovcnt ()); } void print (const void *, size_t); void take (suio *src); void rembytes (size_t n); void iovcb (cb_t cb) { if (uiobytes) uiocbs.push_back (uiocb (nrembytes + uiobytes, cb)); else (*cb) (); } void breakiov () { lastiovend = NULL; } const iovec *iov () const { return iovs.base (); } const iovec *iovlim () const { return iovs.lim (); } size_t iovcnt () const { return iovs.size (); } size_t resid () const { return uiobytes; } u_int64_t iovno () const { return nremiov; } u_int64_t byteno () const { return nrembytes; } int (output) (int fd, int cnt = -1); size_t copyout (void *buf, size_t len) const; size_t copyout (void *buf) const { return copyout (buf, (size_t) -1); } size_t fastspace () const { return scratch_lim - scratch_pos; } int (input) (int fd, size_t len = blocksize); size_t linelen () const; }; inline void suio::pushiov (const void *_base, size_t len) { void *base = const_cast (_base); if (base == lastiovend) { lastiovend += len; iovs.back ().iov_len += len; } else if (len) { iovec *iov = &iovs.push_back (); iov->iov_base = static_cast (base); iov->iov_len = len; lastiovend = static_cast (base) + len; } uiobytes += len; if (base == scratch_pos) { scratch_pos += len; #ifdef CHECK_BOUNDS assert (scratch_pos <= scratch_lim); #endif /* CHECK_BOUNDS */ } } inline char * suio::getspace (size_t n) { if (n <= (size_t) (scratch_lim - scratch_pos)) return scratch_pos; return morescratch (n); } inline char * suio::getspace_aligned (size_t n) { scratch_pos += - reinterpret_cast (scratch_pos) & 3; return getspace (n); } inline void suio::fill (char c, ssize_t n) { if (n <= 0) return; if (n <= scratch_lim - scratch_pos) { memset (scratch_pos, c, n); pushiov (scratch_pos, n); } else slowfill (c, n); } inline void suio::copy (const void *buf, size_t len) { if (len <= (size_t) (scratch_lim - scratch_pos)) { memcpy (scratch_pos, buf, len); pushiov (scratch_pos, len); } else slowcopy (buf, len); } inline size_t suio::linelen () const { size_t n = 0; for (const iovec *v = iov (), *e = iovlim (); v < e; n += v++->iov_len) if (void *p = memchr ((char *) v->iov_base, '\n', v->iov_len)) return n + (static_cast (p) - static_cast (v->iov_base)) + 1; return 0; } size_t iovsize (const iovec *, int); inline void iovscrub (const iovec *iov, int cnt) { const iovec *end = iov + cnt; while (iov < end) bzero (iov->iov_base, iov->iov_len); } /* Suio_printcheck for debugging */ #ifdef DMALLOC void __suio_printcheck (const char *, suio *, const void *, size_t); void __suio_check (const char *, suio *, const void *, size_t); #else /* !DMALLOC */ #define __suio_printcheck(line, uio, buf, len) (uio)->print (buf, len) #endif /* !DMALLOC */ #define suio_printcheck(uio, buf, len) \ __suio_printcheck (__FL__, uio, buf, len) inline void suio::print (const void *buf, size_t len) { #ifdef DMALLOC if (buf != scratch_pos) __suio_check ("suio::print", this, buf, len); #endif /* DMALLOC */ if (len <= smallbufsize && buf != scratch_pos) copy (buf, len); else pushiov (buf, len); } /* Printf */ #ifndef DSPRINTF_DEBUG /* The uprintf functions build up uio structures based on format * strings. String ("%s") arguments are NOT copied, so you must not * modify any strings passed in. Also, a format string of '%m' * doesn't convert any arguments but is equivalent to '%s' with an * argument of strerror (errno). (This is like syslog.) */ extern void suio_vuprintf (struct suio *, const char *, va_list); extern void suio_uprintf (struct suio *, const char *, ...) __attribute__ ((format (printf, 2, 3))); #else /* DSPRINTF_DEBUG */ extern void __suio_vuprintf (const char *, struct suio *, const char *, va_list); #define suio_vuprintf(uio, fmt, ap) __suio_vuprintf (__FL__, uio, fmt, ap) extern void __suio_uprintf (const char *, struct suio *, const char *, ...) __attribute__ ((format (printf, 3, 4))); #define suio_uprintf(uio, args...) __suio_uprintf (__FL__, uio, args) #endif /* DSPRINTF_DEBUG */ /* Compatibility */ #ifdef DMALLOC char *__suio_flatten (const struct suio *, const char *, int); #define suio_flatten(uio) __suio_flatten (uio, __FILE__, __LINE__) #else /* !DMALLOC */ char *suio_flatten (const struct suio *); #endif /* !DMALLOC */ #define suio_fill(uio, c, len) (uio)->fill (c, len) #define suio_copy(uio, buf, len) (uio)->copy (buf, len) #define suio_callback(uio, cb) (uio)->iovcb (cb) inline void suio_print (suio *uio, const void *buf, size_t len) { uio->print (buf, len); } #endif /* !_ASYNC_SUIOXX_H_ */ avenger-0.8.5/util/0000755000175000017500000000000013357046616011144 500000000000000avenger-0.8.5/util/version.c0000644000175000017500000000227211221235216012700 00000000000000/* $Id$ */ /* * * Copyright (C) 2004-2007 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" void version (const char *prog, int quit) { fprintf (stderr, "%s (Mail Avenger) %s\n" "Copyright (C) 2004-2007 David Mazieres\n" "This program comes with NO WARRANTY," " to the extent permitted by law.\n" "You may redistribute it under the terms of" " the GNU General Public License;\n" "see the file named COPYING for details.\n", prog, VERSION); if (quit) exit (0); } avenger-0.8.5/util/Makefile.in0000644000175000017500000006577113357046344013147 00000000000000# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ # $Id$ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = aliascheck$(EXEEXT) dbutil$(EXEEXT) edinplace$(EXEEXT) \ escape$(EXEEXT) synos$(EXEEXT) macutil$(EXEEXT) match$(EXEEXT) \ smtpdcheck$(EXEEXT) noinst_PROGRAMS = omacutil$(EXEEXT) subdir = util ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.in am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(noinst_HEADERS) \ $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LIBRARIES = $(noinst_LIBRARIES) ARFLAGS = cru AM_V_AR = $(am__v_AR_@AM_V@) am__v_AR_ = $(am__v_AR_@AM_DEFAULT_V@) am__v_AR_0 = @echo " AR " $@; am__v_AR_1 = libavutil_a_AR = $(AR) $(ARFLAGS) libavutil_a_LIBADD = am_libavutil_a_OBJECTS = armor.$(OBJEXT) aes.$(OBJEXT) buf.$(OBJEXT) \ clock_gettime.$(OBJEXT) dbexp.$(OBJEXT) flock.$(OBJEXT) \ getopt_long.$(OBJEXT) mdblock.$(OBJEXT) sha1.$(OBJEXT) \ straux.$(OBJEXT) time.$(OBJEXT) version.$(OBJEXT) libavutil_a_OBJECTS = $(am_libavutil_a_OBJECTS) am__installdirs = "$(DESTDIR)$(bindir)" PROGRAMS = $(bin_PROGRAMS) $(noinst_PROGRAMS) am_aliascheck_OBJECTS = aliascheck.$(OBJEXT) aliascheck_dbm.$(OBJEXT) aliascheck_OBJECTS = $(am_aliascheck_OBJECTS) am__DEPENDENCIES_1 = aliascheck_DEPENDENCIES = $(am__DEPENDENCIES_1) $(am__DEPENDENCIES_1) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = aliascheck_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(aliascheck_LDFLAGS) $(LDFLAGS) -o $@ am_dbutil_OBJECTS = dbutil.$(OBJEXT) dbutil_OBJECTS = $(am_dbutil_OBJECTS) dbutil_DEPENDENCIES = $(am__DEPENDENCIES_1) dbutil_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(dbutil_LDFLAGS) $(LDFLAGS) -o $@ am_edinplace_OBJECTS = edinplace.$(OBJEXT) edinplace_OBJECTS = $(am_edinplace_OBJECTS) edinplace_DEPENDENCIES = am_escape_OBJECTS = escape.$(OBJEXT) escape_OBJECTS = $(am_escape_OBJECTS) escape_DEPENDENCIES = am_macutil_OBJECTS = macutil.$(OBJEXT) macutil_OBJECTS = $(am_macutil_OBJECTS) macutil_DEPENDENCIES = am_match_OBJECTS = match.$(OBJEXT) match_OBJECTS = $(am_match_OBJECTS) match_DEPENDENCIES = am_omacutil_OBJECTS = omacutil.$(OBJEXT) omacutil_OBJECTS = $(am_omacutil_OBJECTS) omacutil_DEPENDENCIES = am_smtpdcheck_OBJECTS = smtpdcheck.$(OBJEXT) smtpdcheck_OBJECTS = $(am_smtpdcheck_OBJECTS) smtpdcheck_DEPENDENCIES = am_synos_OBJECTS = synos.$(OBJEXT) synos_OBJECTS = $(am_synos_OBJECTS) synos_DEPENDENCIES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libavutil_a_SOURCES) $(aliascheck_SOURCES) \ $(dbutil_SOURCES) $(edinplace_SOURCES) $(escape_SOURCES) \ $(macutil_SOURCES) $(match_SOURCES) $(omacutil_SOURCES) \ $(smtpdcheck_SOURCES) $(synos_SOURCES) DIST_SOURCES = $(libavutil_a_SOURCES) $(aliascheck_SOURCES) \ $(dbutil_SOURCES) $(edinplace_SOURCES) $(escape_SOURCES) \ $(macutil_SOURCES) $(match_SOURCES) $(omacutil_SOURCES) \ $(smtpdcheck_SOURCES) $(synos_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac HEADERS = $(noinst_HEADERS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in $(top_srcdir)/depcomp DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEBUG = @CXXDEBUG@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CXXNOERR = @CXXNOERR@ CXXWFLAGS = @CXXWFLAGS@ CYGPATH_W = @CYGPATH_W@ DB_DIR = @DB_DIR@ DB_LIB = @DB_LIB@ DEBUG = @DEBUG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECFLAGS = @ECFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ ECXXFLAGS = @ECXXFLAGS@ EGREP = @EGREP@ ETAGS_ARGS = @ETAGS_ARGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDADD = @LDADD@ LDEPS = @LDEPS@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBPCAP = @LIBPCAP@ LIBS = @LIBS@ LIBSASL = @LIBSASL@ LIBSSL = @LIBSSL@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBM_INC = @NDBM_INC@ NDBM_LIBS = @NDBM_LIBS@ NM = @NM@ NMEDIT = @NMEDIT@ NW = @NW@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_LOGGER = @PATH_LOGGER@ PATH_MAIL_LOCAL = @PATH_MAIL_LOCAL@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PERL_POD_MAN = @PERL_POD_MAN@ POD2MAN = @POD2MAN@ RANLIB = @RANLIB@ SED = @SED@ SETUSERCONTEXTLIB = @SETUSERCONTEXTLIB@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ WFLAGS = @WFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ etcdir = @etcdir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ piddir = @piddir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sampledir = @sampledir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ AM_CPPFLAGS = -DAVUTIL_MAIN=1 noinst_LIBRARIES = libavutil.a noinst_HEADERS = avutil.h dbexp.h synos.h vector.h dbutil_SOURCES = dbutil.c dbutil_LDADD = -L. -lavutil $(DB_LIB) dbutil_LDFLAGS = $(LDFLAGS) -static macutil_SOURCES = macutil.c macutil_LDADD = -L. -lavutil omacutil_SOURCES = omacutil.c omacutil_LDADD = -L. -lavutil edinplace_SOURCES = edinplace.c edinplace_LDADD = -L. -lavutil escape_SOURCES = escape.c escape_LDADD = -L. -lavutil aliascheck_SOURCES = aliascheck.c aliascheck_dbm.c aliascheck_LDADD = -L. -lavutil $(DB_LIB) $(NDBM_LIBS) # We make this -static (meaning libtool archives static) # because we don't want to start failing when someone updates # the sleepycat database on the system aliascheck_LDFLAGS = $(LDFLAGS) -static smtpdcheck_SOURCES = smtpdcheck.c smtpdcheck_LDADD = -L. -lavutil match_SOURCES = match.c match_LDADD = -L. -lavutil synos_SOURCES = synos.c synos_LDADD = -L. -lavutil libavutil_a_SOURCES = armor.c aes.c buf.c clock_gettime.c dbexp.c \ flock.c getopt_long.c mdblock.c sha1.c straux.c time.c version.c CLEANFILES = core *.core *~ EXTRA_DIST = .gitignore omacutil.c MAINTAINERCLEANFILES = Makefile.in all: all-am .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu util/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu util/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLIBRARIES: -test -z "$(noinst_LIBRARIES)" || rm -f $(noinst_LIBRARIES) libavutil.a: $(libavutil_a_OBJECTS) $(libavutil_a_DEPENDENCIES) $(EXTRA_libavutil_a_DEPENDENCIES) $(AM_V_at)-rm -f libavutil.a $(AM_V_AR)$(libavutil_a_AR) libavutil.a $(libavutil_a_OBJECTS) $(libavutil_a_LIBADD) $(AM_V_at)$(RANLIB) libavutil.a install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list clean-noinstPROGRAMS: @list='$(noinst_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list aliascheck$(EXEEXT): $(aliascheck_OBJECTS) $(aliascheck_DEPENDENCIES) $(EXTRA_aliascheck_DEPENDENCIES) @rm -f aliascheck$(EXEEXT) $(AM_V_CCLD)$(aliascheck_LINK) $(aliascheck_OBJECTS) $(aliascheck_LDADD) $(LIBS) dbutil$(EXEEXT): $(dbutil_OBJECTS) $(dbutil_DEPENDENCIES) $(EXTRA_dbutil_DEPENDENCIES) @rm -f dbutil$(EXEEXT) $(AM_V_CCLD)$(dbutil_LINK) $(dbutil_OBJECTS) $(dbutil_LDADD) $(LIBS) edinplace$(EXEEXT): $(edinplace_OBJECTS) $(edinplace_DEPENDENCIES) $(EXTRA_edinplace_DEPENDENCIES) @rm -f edinplace$(EXEEXT) $(AM_V_CCLD)$(LINK) $(edinplace_OBJECTS) $(edinplace_LDADD) $(LIBS) escape$(EXEEXT): $(escape_OBJECTS) $(escape_DEPENDENCIES) $(EXTRA_escape_DEPENDENCIES) @rm -f escape$(EXEEXT) $(AM_V_CCLD)$(LINK) $(escape_OBJECTS) $(escape_LDADD) $(LIBS) macutil$(EXEEXT): $(macutil_OBJECTS) $(macutil_DEPENDENCIES) $(EXTRA_macutil_DEPENDENCIES) @rm -f macutil$(EXEEXT) $(AM_V_CCLD)$(LINK) $(macutil_OBJECTS) $(macutil_LDADD) $(LIBS) match$(EXEEXT): $(match_OBJECTS) $(match_DEPENDENCIES) $(EXTRA_match_DEPENDENCIES) @rm -f match$(EXEEXT) $(AM_V_CCLD)$(LINK) $(match_OBJECTS) $(match_LDADD) $(LIBS) omacutil$(EXEEXT): $(omacutil_OBJECTS) $(omacutil_DEPENDENCIES) $(EXTRA_omacutil_DEPENDENCIES) @rm -f omacutil$(EXEEXT) $(AM_V_CCLD)$(LINK) $(omacutil_OBJECTS) $(omacutil_LDADD) $(LIBS) smtpdcheck$(EXEEXT): $(smtpdcheck_OBJECTS) $(smtpdcheck_DEPENDENCIES) $(EXTRA_smtpdcheck_DEPENDENCIES) @rm -f smtpdcheck$(EXEEXT) $(AM_V_CCLD)$(LINK) $(smtpdcheck_OBJECTS) $(smtpdcheck_LDADD) $(LIBS) synos$(EXEEXT): $(synos_OBJECTS) $(synos_DEPENDENCIES) $(EXTRA_synos_DEPENDENCIES) @rm -f synos$(EXEEXT) $(AM_V_CCLD)$(LINK) $(synos_OBJECTS) $(synos_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/aes.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/aliascheck.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/aliascheck_dbm.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/armor.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/buf.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/clock_gettime.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dbexp.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/dbutil.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/edinplace.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/escape.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/flock.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/getopt_long.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/macutil.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/match.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/mdblock.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/omacutil.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sha1.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/smtpdcheck.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/straux.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/synos.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/time.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/version.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LIBRARIES) $(PROGRAMS) $(HEADERS) installdirs: for dir in "$(DESTDIR)$(bindir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool \ clean-noinstLIBRARIES clean-noinstPROGRAMS mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-exec-hook install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) uninstall-hook .MAKE: install-am install-exec-am install-strip uninstall-am .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libtool \ clean-noinstLIBRARIES clean-noinstPROGRAMS cscopelist-am ctags \ ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-exec-hook install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-hook .PRECIOUS: Makefile $(PROGRAMS): libavutil.a aliascheck_dbm.o: $(srcdir)/aliascheck_dbm.c $(srcdir)/avutil.h $(COMPILE) $(NDBM_INC) -c $(srcdir)/aliascheck_dbm.c install-exec-hook: rm -f $(DESTDIR)$(bindir)/sendmac$(EXEEXT) ln $(DESTDIR)$(bindir)/macutil$(EXEEXT) \ $(DESTDIR)$(bindir)/sendmac$(EXEEXT) uninstall-hook: rm -f $(DESTDIR)$(bindir)/sendmac$(EXEEXT) # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: avenger-0.8.5/util/aliascheck_dbm.c0000644000175000017500000000365211221235216014127 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #ifndef HAVE_NDBM int check_alias_dbm (const char *file, const char *user, int map) { return 2; } #else /* HAVE_NDBM */ #include int check_alias_dbm (const char *file, const char *user, int map) { DBM *db; datum k, v; int len = strlen (file); char *dbfile; if (len < 4 && strcmp (file + len - 3, ".db")) return 2; dbfile = xmalloc (len + 1); strcpy (dbfile, file); dbfile[len - 3] = '\0'; errno = 0; db = dbm_open (dbfile, DBM_RDONLY, 0666); free (dbfile); if (!db) { if (errno) perror (file); return 2; } if (!map) { /* Only alias files have the special "@" record */ k.dptr = "@"; k.dsize = 2; v = dbm_fetch (db, k); if (!v.dptr) { fprintf (stderr, "%s: incomplete/corrupted alias database\n", file); dbm_close (db); return 2; } } k.dptr = (char *) user; k.dsize = strlen (user); /* Only alias files include trailing nul byte */ if (!map) k.dsize++; v = dbm_fetch (db, k); if (!v.dptr) { dbm_close (db); return 1; } printf ("%.*s\n", (int) v.dsize, (char *) v.dptr); dbm_close (db); return 0; } #endif /* HAVE_NDBM */ avenger-0.8.5/util/synos.c0000644000175000017500000002013511221235216012364 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "util/synos.h" u_int32_t synos_mtu = 1500; void synos_clearfp (fpdat_t *fpp) { VECTOR_CLEAR (&fpp->fp_opts); VECTOR_INIT (&fpp->fp_opts); } void synos_clearos (osdat_t *odp) { free (odp->od_name); odp->od_name = NULL; VECTOR_CLEAR (&odp->od_opts); VECTOR_INIT (&odp->od_opts); } int synos_check (const fpdat_t *fpp, const osdat_t *odp) { int i; u_int32_t mss = 0; int mss_valid = 0; if (fpp->fp_ttl > odp->od_ttl || fpp->fp_ttl + 40 < odp->od_ttl) return 0; if (fpp->fp_df != odp->od_df) return 0; if (fpp->fp_size != odp->od_size) return 0; if (fpp->fp_opts.v_size != odp->od_opts.v_size) return 0; for (i = 0; i < fpp->fp_opts.v_size; i++) { switch (odp->od_opts.v_vec[i].o_type) { case OPT_M: if (fpp->fp_opts.v_vec[i].o_type != OPT_M) return 0; mss = fpp->fp_opts.v_vec[i].o_val; mss_valid = 1; if (mss != odp->od_opts.v_vec[i].o_val) return 0; break; case OPT_MMOD: if (fpp->fp_opts.v_vec[i].o_type != OPT_M) return 0; mss = fpp->fp_opts.v_vec[i].o_val; mss_valid = 1; if (mss % odp->od_opts.v_vec[i].o_val) return 0; break; case OPT_MSTAR: if (fpp->fp_opts.v_vec[i].o_type != OPT_M) return 0; mss = fpp->fp_opts.v_vec[i].o_val; mss_valid = 1; break; default: if (odp->od_opts.v_vec[i].o_type != fpp->fp_opts.v_vec[i].o_type) return 0; break; } } switch (odp->od_wintype) { case WIN_ANY: break; case WIN_EQ: if (fpp->fp_win != odp->od_win) return 0; break; case WIN_S: if ((!synos_mtu || fpp->fp_win != odp->od_win * (synos_mtu - 40)) && (!mss_valid || fpp->fp_win != odp->od_win * mss)) return 0; break; case WIN_T: if ((!synos_mtu || fpp->fp_win != odp->od_win * synos_mtu) && (!mss_valid || fpp->fp_win != odp->od_win * (mss + 40))) return 0; case WIN_MOD: if (fpp->fp_win % odp->od_win) return 0; break; } return 1; } int synos_parsefp (fpdat_t *fpp, const char *fps) { int n; const char *s = fps; VECTOR_CLEAR (&fpp->fp_opts); VECTOR_INIT (&fpp->fp_opts); if (sscanf (s, "%u:%u:%d:%d%n", &fpp->fp_win, &fpp->fp_ttl, &fpp->fp_df, &fpp->fp_size, &n) != 4) return 0; s += n; for (;;) { tcpopt_t *opp; if (!*s || (s[0] == ':' && s[1] == '\0')) return 1; if (*s != ':' && *s != ',') return 0; s++; opp = VECTOR_NEXT (&fpp->fp_opts); switch (*s++) { case 'N': opp->o_type = OPT_N; break; case 'W': if (sscanf (s, "%u%n", &opp->o_val, &n) != 1) return 0; opp->o_type = OPT_W; s += n; break; case 'M': if (sscanf (s, "%u%n", &opp->o_val, &n) != 1) return 0; opp->o_type = OPT_M; s += n; break; case 'S': opp->o_type = OPT_S; break; case 'T': if (*s == '0') { opp->o_type = OPT_T0; s++; } else opp->o_type = OPT_T; break; default: return 0; } } } int synos_parseos (osdat_t *odp, const char *line) { int n; const char *s = line; int begin = 1; if (!*s || *s == '#' || *s == '\n') return -1; VECTOR_CLEAR (&odp->od_opts); VECTOR_INIT (&odp->od_opts); free (odp->od_name); odp->od_name = NULL; if (*s == '*') { odp->od_wintype = WIN_ANY; s++; } else { if (*s == '%') odp->od_wintype = WIN_MOD; else if (*s == 'S') odp->od_wintype = WIN_S; else if (*s == 'T') odp->od_wintype = WIN_T; else { odp->od_wintype = WIN_EQ; s--; } s++; if (sscanf (s, "%u%n", &odp->od_win, &n) != 1) return 0; s += n; } if (sscanf (s, ":%u:%d:%d:%n", &odp->od_ttl, &odp->od_df, &odp->od_size, &n) != 3) return 0; s += n - 1; for (;;) { tcpopt_t *opp; if (!*s) return 0; if (*s == ':' && !begin) break; if (*s != ':' && *s != ',') return 0; s++; if (begin && *s == '.') { s++; break; } begin = 0; opp = VECTOR_NEXT (&odp->od_opts); switch (*s++) { case 'N': opp->o_type = OPT_N; break; case 'W': if (*s == '*') { s++; opp->o_type = OPT_WSTAR; break; } if (*s == '%') { opp->o_type = OPT_WMOD; s++; } else opp->o_type = OPT_W; if (sscanf (s, "%u%n", &opp->o_val, &n) != 1) return 0; s += n; break; case 'M': if (*s == '*') { s++; opp->o_type = OPT_MSTAR; break; } if (*s == '%') { opp->o_type = OPT_MMOD; s++; } else opp->o_type = OPT_M; if (sscanf (s, "%u%n", &opp->o_val, &n) != 1) return 0; s += n; break; case 'S': opp->o_type = OPT_S; break; case 'T': if (*s == '0') { opp->o_type = OPT_T0; s++; } else opp->o_type = OPT_T; break; default: return 0; } } if ((s = strrchr (s, ':'))) { odp->od_name = xstrdup (s + 1); n = strlen (odp->od_name); if (n > 0 && odp->od_name[n - 1] == '\n') odp->od_name[n - 1] = '\0'; return 1; } return 0; } #ifdef AVUTIL_MAIN #include "getopt_long.h" char *progname; const char *opt_fpdb = DATADIR "/pf.os"; int opt_verbose; static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s [--mtu MTU] [--db FPDB] fingerprint\n", progname); exit (1); } static int lookup (const char *fps) { fpdat_t fp; osdat_t os; FILE *f; struct lnbuf buf; int line = 0; bzero (&fp, sizeof (fp)); bzero (&os, sizeof (os)); bzero (&buf, sizeof (buf)); if (!synos_parsefp (&fp, fps)) { fprintf (stderr, "bad fingerprint '%s'\n", fps); synos_clearfp (&fp); return 1; } if (!(f = fopen (opt_fpdb, "r"))) { perror (opt_fpdb); exit (1); } while (readln (&buf, f, (size_t) -1) == LNBUF_OK) { int r = synos_parseos (&os, buf.buf); line++; if (r < 0) continue; if (r == 0) { fprintf (stderr, "%s:%d: syntax error\n", opt_fpdb, line); continue; } if (synos_check (&fp, &os)) { if (opt_verbose) printf ("%40s %s\n", fps, os.od_name); else printf ("%s\n", os.od_name); synos_clearfp (&fp); synos_clearos (&os); fclose (f); return 0; } } if (opt_verbose) printf ("%40s unknown\n", fps); synos_clearfp (&fp); synos_clearos (&os); fclose (f); return 1; } int main (int argc, char **argv) { struct option o[] = { { "version", no_argument, NULL, 256 + 'v' }, { "mtu", required_argument, NULL, 'm' }, { "db", required_argument, NULL, 'd' }, { NULL, 0, NULL, 0 } }; int c; int opt_fpdb_set = 0; progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; while ((c = getopt_long (argc, argv, "+v", o, NULL)) != -1) switch (c) { case 'd': opt_fpdb = optarg; opt_fpdb_set = 1; break; case 'm': synos_mtu = atoi (optarg); if ((synos_mtu && synos_mtu < 40) || synos_mtu >= 0x10000) usage (); case 'v': opt_verbose = 1; break; case 256 + 'v': version (progname, 1); break; default: usage (); break; } if (!opt_verbose && optind + 1 != argc) usage (); if (!opt_fpdb_set && access (opt_fpdb, 0) && !access ("/etc/pf.os", 0)) opt_fpdb = "/etc/pf.os"; while (optind < argc) lookup (argv[optind++]); return 0; } #endif /* AVUTIL_MAIN */ avenger-0.8.5/util/synos.h0000644000175000017500000000370511221235216012375 00000000000000/* $Id$ */ /* * * Copyright (C) 2003 David Mazieres (dm@uun.org) * * 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 _SYNOS_H_ #define _SYNOS_H_ 1 #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #include "vector.h" #ifdef AVUTIL_MAIN #include "avutil.h" #else /* !AVUTIL_MAIN */ #include "sysconf.h" #endif /* !AVUTIL_MAIN */ extern u_int32_t synos_mtu; typedef struct tcpopt { enum { OPT_NONE, OPT_M, OPT_MMOD, OPT_MSTAR, OPT_N, OPT_T, OPT_T0, OPT_S, OPT_W, OPT_WMOD, OPT_WSTAR } o_type; u_int32_t o_val; } tcpopt_t; typedef struct fpdat { u_int32_t fp_win; u_int32_t fp_ttl; int fp_df; int fp_size; VECTOR (tcpopt_t) fp_opts; } fpdat_t; typedef struct osdat { char *od_name; enum { WIN_ANY, WIN_EQ, WIN_MOD, WIN_S, WIN_T } od_wintype; u_int32_t od_win; u_int32_t od_ttl; int od_df; int od_size; VECTOR (tcpopt_t) od_opts; } osdat_t; void synos_clearfp (fpdat_t *fpp); void synos_clearos (osdat_t *odp); int synos_check (const fpdat_t *fpp, const osdat_t *odp); /* Note, you must bzero fdp / odp before calling these functions for * the first time, and call synos_clearXX after the last time. */ int synos_parsefp (fpdat_t *fpp, const char *fps); int synos_parseos (osdat_t *odp, const char *line); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* !_SYNOS_H_ */ avenger-0.8.5/util/time.c0000644000175000017500000000332611221235216012152 00000000000000/* $Id$ */ /* * * Copyright (C) 2003 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" long parse_expire (const char *age, time_t now) { unsigned long res = -1; char mult; unsigned int len; int sign = 1; if (age[0] == '+') age++; else if (age[0] == '-') { sign = -1; age++; } else if (sscanf (age, "%lu%n", &res, &len) == 1 && len == strlen (age)) return res; if (sscanf (age, "%lu%c%n", &res, &mult, &len) != 2 || len != strlen (age)) { fprintf (stderr, "bad time %s\n", age); return -1; } if (sign < 0) res = -res; switch (mult) { case 'Y': res *= 365 * 24 * 60 * 60; break; case 'M': res *= 30 * 24 * 60 * 60; break; case 'W': case 'w': res *= 7 * 24 * 60 * 60; break; case 'D': case 'd': res *= 24 * 60 * 60; break; case 'h': res *= 60 * 60; break; case 'm': res *= 60; break; case 's': break; default: fprintf (stderr, "unknown age unit '%c'\n", mult); return -1; } return now + res; } avenger-0.8.5/util/escape.c0000644000175000017500000000420011221235216012444 00000000000000/* $Id$ */ /* * * Copyright (C) 2005 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include "getopt_long.h" char *progname; const char shellspec[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, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, }; void escape (const char *_s) { const unsigned char *s = (const unsigned char *) _s; while (*s) { if (*s < sizeof (shellspec) && shellspec[*s]) printf ("\\"); printf ("%c", *s++); } printf ("\n"); } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s string\n", progname); exit (1); } int main (int argc, char **argv) { struct option o[] = { { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; int c; progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; while ((c = getopt_long (argc, argv, "+", o, NULL)) != -1) switch (c) { case 'v': version (progname, 1); exit (0); /* XXX */ break; default: usage (); break; } if (optind + 1 != argc) usage (); escape (argv[optind]); exit (0); } avenger-0.8.5/util/armor.c0000644000175000017500000002150011221235216012326 00000000000000/* $Id$ */ /* * * Copyright (C) 1999 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" static const char b2a32[32] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9', }; static const signed char a2b32[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, 11, 12, -1, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1, 11, 12, -1, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; static const int b2a32rem[5] = {0, 2, 4, 5, 7}; static const int a2b32rem[8] = {0, -1, 1, -1, 2, 3, -1, 4}; /* 0 1 2 3 4 5 6 7 * 0 5 3 * 1 2 5 1 * 2 4 4 * 3 1 5 2 * 4 3 5 */ char * armor32 (const void *dp, size_t dl) { const u_char *p = dp; int rem = dl % 5; const u_char *e = p + (dl - rem); size_t reslen = (dl / 5) * 8 + b2a32rem[rem]; char *res = malloc (reslen + 1); char *d = res; if (!res) return NULL; while (p < e) { d[0] = b2a32[p[0] >> 3]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[3] = b2a32[(p[1] & 0x1) << 4 | p[2] >> 4]; d[4] = b2a32[(p[2] & 0xf) << 1 | p[3] >> 7]; d[5] = b2a32[p[3] >> 2 & 0x1f]; d[6] = b2a32[(p[3] & 0x3) << 3 | p[4] >> 5]; d[7] = b2a32[p[4] & 0x1f]; p += 5; d += 8; } switch (rem) { case 4: d[6] = b2a32[(p[3] & 0x3) << 3]; d[5] = b2a32[p[3] >> 2 & 0x1f]; d[4] = b2a32[(p[2] & 0xf) << 1 | p[3] >> 7]; d[3] = b2a32[(p[1] & 0x1) << 4 | p[2] >> 4]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[0] = b2a32[p[0] >> 3]; d += 7; break; case 3: d[4] = b2a32[(p[2] & 0xf) << 1]; d[3] = b2a32[(p[1] & 0x1) << 4 | p[2] >> 4]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[0] = b2a32[p[0] >> 3]; d += 5; break; case 2: d[3] = b2a32[(p[1] & 0x1) << 4]; d[2] = b2a32[p[1] >> 1 & 0x1f]; d[1] = b2a32[(p[0] & 0x7) << 2 | p[1] >> 6]; d[0] = b2a32[p[0] >> 3]; d += 4; break; case 1: d[1] = b2a32[(p[0] & 0x7) << 2]; d[0] = b2a32[p[0] >> 3]; d += 2; break; } assert (d == res + reslen); *d = '\0'; return res; } ssize_t armor32len (const char *_s) { const u_char *s = (const u_char *) _s; const u_char *p = s; ssize_t len; while (a2b32[*p] >= 0) p++; len = p - s; return a2b32rem[len & 7] < 0 ? -1 : len; } ssize_t dearmor32len (const char *s) { ssize_t len = armor32len (s); return len < 0 ? -1 : (len >> 3) * 5 + a2b32rem[len & 7]; } ssize_t dearmor32 (void *out, const char *_s) { const u_char *s = (const u_char *) _s; ssize_t len = armor32len (_s); int rem = a2b32rem [len & 7]; size_t outlen = (len >> 3) * 5 + rem; char *d = out; int c0, c1, c2, c3, c4, c5, c6, c7; const u_char *e; if (rem < 0) return -1; if (len <= 0) return 0; for (e = s + (len & ~7); s < e; s += 8, d += 5) { c0 = a2b32[s[0]]; c1 = a2b32[s[1]]; d[0] = c0 << 3 | c1 >> 2; c2 = a2b32[s[2]]; c3 = a2b32[s[3]]; d[1] = c1 << 6 | c2 << 1 | c3 >> 4; c4 = a2b32[s[4]]; d[2] = c3 << 4 | c4 >> 1; c5 = a2b32[s[5]]; c6 = a2b32[s[6]]; d[3] = c4 << 7 | c5 << 2 | c6 >> 3; c7 = a2b32[s[7]]; d[4] = c6 << 5 | c7; } if (rem >= 1) { c0 = a2b32[s[0]]; c1 = a2b32[s[1]]; *d++ = c0 << 3 | c1 >> 2; if (rem >= 2) { c2 = a2b32[s[2]]; c3 = a2b32[s[3]]; *d++ = c1 << 6 | c2 << 1 | c3 >> 4; if (rem >= 3) { c4 = a2b32[s[4]]; *d++ = c3 << 4 | c4 >> 1; if (rem >= 4) { c5 = a2b32[s[5]]; c6 = a2b32[s[6]]; *d++ = c4 << 7 | c5 << 2 | c6 >> 3; } } } } assert (d == (char *) out + outlen); return len; } static const char b2a64[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; static const signed char a2b64[256] = { -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, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; char * armor64 (const void *dp, size_t len) { const u_char *p = dp; int rem = len % 3; const u_char *e = p + (len - rem); size_t reslen = ((len + 2) / 3) * 4; char *res = malloc (reslen + 1); char *d = res; while (p < e) { d[0] = b2a64[p[0] >> 2]; d[1] = b2a64[(p[0] & 0x3) << 4 | p[1] >> 4]; d[2] = b2a64[(p[1] & 0xf) << 2 | p[2] >> 6]; d[3] = b2a64[p[2] & 0x3f]; d += 4; p += 3; } switch (rem) { case 1: d[0] = b2a64[p[0] >> 2]; d[1] = b2a64[(p[0] & 0x3) << 4]; d[2] = d[3] = '='; d += 4; break; case 2: d[0] = b2a64[p[0] >> 2]; d[1] = b2a64[(p[0] & 0x3) << 4 | p[1] >> 4]; d[2] = b2a64[(p[1] & 0xf) << 2]; d[3] = '='; d += 4; break; } assert (d == res + reslen); *d = '\0'; return res; } ssize_t armor64len (const char *_s) { const u_char *s = (const u_char *) _s; const u_char *p = s; ssize_t len; while (a2b64[*p] >= 0) p++; if (*p == '=') p++; if (*p == '=') p++; len = p - s; return (len & 3) ? -1 : len; } ssize_t dearmor64len (const char *_s) { const u_char *s = (const u_char *) _s; const u_char *p = s; ssize_t len; while (a2b64[*p] >= 0) p++; len = p - s; switch (len & 3) { case 0: return (len >> 2) * 3; case 2: return p[0] == '=' && p[1] == '=' ? (len >> 2) * 3 + 1 : -1; case 3: return p[0] == '=' ? (len >> 2) * 3 + 2 : -1; } return -1; } ssize_t dearmor64 (void *out, const char *_s) { const u_char *s = (const u_char *) _s; ssize_t outlen = dearmor64len (_s); ssize_t len = ((outlen + 2) / 3) * 4; char *d = out; int c0, c1, c2, c3; const u_char *e; if (outlen < 0) return -1; if (len <= 0) return len; for (e = s + len - 4; s < e; s += 4, d += 3) { c0 = a2b64[s[0]]; c1 = a2b64[s[1]]; d[0] = c0 << 2 | c1 >> 4; c2 = a2b64[s[2]]; d[1] = c1 << 4 | c2 >> 2; c3 = a2b64[s[3]]; d[2] = c2 << 6 | c3; } c0 = a2b64[s[0]]; c1 = a2b64[s[1]]; *d++ = c0 << 2 | c1 >> 4; if ((c2 = a2b64[s[2]]) >= 0) { *d++ = c1 << 4 | c2 >> 2; if ((c3 = a2b64[s[3]]) >= 0) *d++ = c2 << 6 | c3; } *d = '\0'; return len; } avenger-0.8.5/util/avutil.h0000644000175000017500000001637311221235216012533 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 _AVUTIL_H_ #define _AVUTIL_H_ 1 #include #include #include #include #include #include #include #include #include #ifdef HAVE_SYS_FILE_H # include #endif /* HAVE_SYS_FILE_H */ #ifdef TIME_WITH_SYS_TIME # include # include #elif defined (HAVE_SYS_TIME_H) # include #else /* !TIME_WITH_SYS_TIME && !HAVE_SYS_TIME_H */ # include #endif /* !TIME_WITH_SYS_TIME && !HAVE_SYS_TIME_H */ #ifdef HAVE_TIMES # include #endif /* HAVE_TIMES */ #ifndef HAVE_CLOCK_GETTIME_DECL int clock_gettime (int, struct timespec *); #endif /* !HAVE_CLOCK_GETTIME_DECL */ #ifndef HAVE_CLOCK_GETTIME # undef CLOCK_REALTIME # undef CLOCK_VIRTUAL # undef CLOCK_PROF #endif /* !HAVE_CLOCK_GETTIME */ #ifndef CLOCK_REALTIME # define CLOCK_REALTIME 0 #endif /* !CLOCK_REALTIME */ #ifndef CLOCK_VIRTUAL # define CLOCK_VIRTUAL 1 #endif /* !CLOCK_VIRTUAL */ #ifndef CLOCK_PROF # define CLOCK_PROF 2 #endif /* !CLOCK_PROF */ #ifndef HAVE_INT32_T typedef int int32_t; #endif /* !HAVE_INT32_T */ #ifndef HAVE_U_INT32_T typedef unsigned int u_int32_t; #endif /* !HAVE_U_INT32_T */ #ifndef HAVE_INT64_T # if SIZEOF_LONG == 8 typedef long int64_t; # elif SIZEOF_LONG_LONG == 8 typedef long long int64_t; # else /* Can't find 64-bit type */ # error "Cannot find any 64-bit data types" # endif /* !SIZEOF_LONG_LONG */ #endif /* !HAVE_INT64_T */ #ifndef HAVE_U_INT64_T # if SIZEOF_LONG == 8 typedef unsigned long u_int64_t; # elif SIZEOF_LONG_LONG == 8 typedef unsigned long long u_int64_t; # else /* Can't find 64-bit type */ # error "Cannot find any 64-bit data types" # endif /* !SIZEOF_LONG_LONG */ # define HAVE_U_INT64_T 1 /* XXX */ #endif /* !HAVE_INT64_T */ #if STDC_HEADERS # include # ifndef bzero # define bzero(a,b) memset((a), 0, (b)) # endif /* !bzero */ #else /* !STDC_HEADERS */ # ifndef DMALLOC # ifndef HAVE_STRCHR # define strchr index # define strrchr rindex # endif /* !HAVE_STRCHR */ # ifdef __cplusplus char *strchr (const char *, int); char *strrchr (const char *, int); # else /* !__cplusplus */ char *strchr (); char *strrchr (); # endif /* !__cplusplus */ # ifdef HAVE_MEMCPY # define bzero(a,b) memset((a), 0, (b)) # else /* !HAVE_MEMCPY */ # define memcpy(d, s, n) bcopy ((s), (d), (n)) # define memmove(d, s, n) bcopy ((s), (d), (n)) # endif /* !HAVE_MEMCPY */ # endif /* !DMALLOC */ #endif #if __GNUC__ < 2 # ifndef __attribute__ # define __attribute__(x) # endif /* !__attribute__ */ #endif /* !gcc 2 */ #include /* constants for flock */ #ifndef LOCK_SH # define LOCK_SH 1 /* shared lock */ # define LOCK_EX 2 /* exclusive lock */ # define LOCK_NB 4 /* don't block when locking */ # define LOCK_UN 8 /* unlock */ #endif /* !LOCK_SH */ #ifdef NEED_FLOCK_DECL int flock (int fd, int operation); #endif /* NEED_FLOCK_DECL */ #ifndef HAVE_PREAD_DECL ssize_t pread(int, void *, size_t, off_t); #endif /* !HAVE_PREAD_DECL */ #ifndef HAVE_PWRITE_DECL ssize_t pwrite(int, const void *, size_t, off_t); #endif /* !HAVE_PWRITE_DECL */ static inline void putint (void *_dp, u_int32_t val) { unsigned char *dp = (unsigned char *) (_dp); dp[0] = val >> 24; dp[1] = val >> 16; dp[2] = val >> 8; dp[3] = val; } static inline u_int32_t getint (const void *_dp) { const unsigned char *dp = (const unsigned char *) (_dp); return dp[0] << 24 | dp[1] << 16 | dp[2] << 8 | dp[3]; } static inline void putshort (void *_dp, u_int16_t val) { unsigned char *dp = (unsigned char *) (_dp); dp[0] = val >> 8; dp[1] = val; } static inline u_int16_t getshort (const void *_dp) { const unsigned char *dp = (const unsigned char *) (_dp); return dp[0] << 8 | dp[1]; } #ifdef DMALLOC #include #endif /* DMALLOC */ #ifndef xmalloc static inline void * xmalloc (size_t n) { void *p = malloc (n); if (!p) { fprintf (stderr, "out of memory allocating %lu bytes\n", (unsigned long) n); abort (); } return p; } #endif /* xmalloc */ #ifndef xstrdup static inline char * xstrdup (const char *s) { char *ret = xmalloc (strlen (s) + 1); return strcpy (ret, s); } #endif /* !xstrdup */ #ifndef xrealloc static inline void * xrealloc (void *p, size_t n) { void *r = realloc (p, n); if (!r) { fprintf (stderr, "out of memory in xrealloc\n"); abort (); } return r; } #endif /* !xrealloc */ /* version.c */ void version (const char *prog, int quit); /* time.c */ long parse_expire (const char *age, time_t now); /* straux.c */ char *mempbrk (char *, const char *, int); char *xstrsep (char **, const char *); char *strnnsep (char **, const char *); /* aes.c */ struct aes_ctx { int nrounds; u_int32_t e_key[60]; u_int32_t d_key[60]; }; typedef struct aes_ctx aes_ctx; void aes_setkey (aes_ctx *aes, const void *key, u_int keylen); void aes_encrypt (const aes_ctx *aes, void *buf, const void *ibuf); void aes_decrypt (const aes_ctx *aes, void *buf, const void *ibuf); /* mdblock.c */ struct mdblock { u_int64_t count; void (*consume) (struct mdblock *, const unsigned char block[64]); unsigned char buffer[64]; }; typedef struct mdblock mdblock; void mdblock_init (mdblock *mp, void (*consume) (mdblock *, const unsigned char block[64])); void mdblock_update (mdblock *mp, const void *bytes, size_t len); void mdblock_finish (mdblock *mp, int bigendian); /* sha1.c */ struct sha1_ctx { mdblock mdb; u_int32_t state[5]; }; typedef struct sha1_ctx sha1_ctx; enum { sha1_hashsize = 20 }; void sha1_init (sha1_ctx *sc); void sha1_update (sha1_ctx *sc, const void *bytes, size_t len); void sha1_final (sha1_ctx *sc, unsigned char out[20]); void hmac_sha1 (void *out, const char *key, const void *data, u_int dlen); /* armor.c */ char *armor32 (const void *dp, size_t dl); ssize_t dearmor32len (const char *s); ssize_t dearmor32 (void *out, const char *s); char *armor64 (const void *dp, size_t len); ssize_t dearmor64len (const char *s); ssize_t dearmor64 (void *out, const char *s); /* buf.c */ enum lnbuf_res { LNBUF_OK = 1, /* Returned line in buffer */ LNBUF_EOF = 0, /* Normal end of file */ LNBUF_EOFNL = -1, /* Last line of file has no newline */ LNBUF_NOMEM = -2, /* Malloc failed */ LNBUF_TOOBIG = -3, /* Maximum requested line size exceeded */ LNBUF_IOERR = -4, /* I/O error */ }; struct lnbuf { char *buf; /* Line of text */ size_t size; /* Length of line */ size_t alloc; /* Number of bytes allocated */ }; int readln (struct lnbuf *res, FILE *fp, size_t maxbuf); #endif /* !_AVUTIL_H_ */ avenger-0.8.5/util/straux.c0000644000175000017500000001147611221235216012547 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" /* This is the memory equivalent of strpbrk(). It finds the first * occurance of any character from s2 in s1, but takes a length * argument for s1 rather than stopping at a null byte. */ char * mempbrk (char *s1, const char *s2, int len) { const char *const eom = s1 + len; register const char *cp; register int i1, i2; while (s1 < eom) { i1 = *s1++; cp = s2; while ((i2 = *cp++)) if (i1 == i2) return (s1 - 1); } return (NULL); } /* This is a strsep function that returns a null field for adjacent * separators. This is the same as the 4.4BSD strsep, but different * from the one in the GNU libc. */ char * xstrsep(char **str, const char *delim) { char *s, *e; if (!**str) return (NULL); s = *str; e = s + strcspn (s, delim); if (*e != '\0') *e++ = '\0'; *str = e; return (s); } /* Get the next non-null token (like GNU strsep). Strsep() will * return a null token for two adjacent separators, so we may have to * loop. */ char * strnnsep (char **stringp, const char *delim) { char *tok; do { tok = xstrsep (stringp, delim); } while (tok && *tok == '\0'); return (tok); } #ifndef HAVE_STRCASECMP /* * This array is designed for mapping upper and lower case letter * together for a case independent comparison. The mappings are * based upon ascii character sequences. */ static const u_char charmap[] = { '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247', '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257', '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267', '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277', '\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307', '\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317', '\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327', '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377', }; int strcasecmp (const char *s1, const char *s2) { const u_char *cm = charmap, *us1 = (const u_char *) s1, *us2 = (const u_char *) s2; while (cm[*us1] == cm[*us2++]) if (*us1++ == '\0') return (0); return (cm[*us1] - cm[*--us2]); } int strncasecmp (const char *s1, const char *s2, int n) { if (n != 0) { const u_char *cm = charmap, *us1 = (const u_char *) s1, *us2 = (const u_char *) s2; do { if (cm[*us1] != cm[*us2++]) return (cm[*us1] - cm[*--us2]); if (*us1++ == '\0') break; } while (--n != 0); } return (0); } #endif /* !HAVE_STRCASECMP */ avenger-0.8.5/util/buf.c0000644000175000017500000000334411221235216011770 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" /* Note: Unfortunately this doesn't deal with lines containing '\0' * characters. */ int readln (struct lnbuf *res, FILE *fp, size_t maxbuf) { if (!res->alloc) { res->alloc = 128; res->buf = xmalloc (res->alloc); } if (!fgets (res->buf, res->alloc, fp)) { res->size = 0; return ferror (fp) ? LNBUF_IOERR : LNBUF_EOF; } for (;;) { size_t newalloc; res->size = strlen (res->buf); if (res->size && res->buf[res->size - 1] == '\n') return LNBUF_OK; else if (res->size < res->alloc - 1) return LNBUF_EOFNL; newalloc = res->alloc * 2; if (newalloc > maxbuf) newalloc = maxbuf; if (newalloc < res->alloc) newalloc = res->alloc; if (newalloc <= res->alloc) return LNBUF_TOOBIG; res->buf = xrealloc (res->buf, newalloc); res->alloc = newalloc; if (!fgets (res->buf + res->size, res->alloc - res->size, fp)) return ferror (fp) ? LNBUF_IOERR : LNBUF_EOFNL; } } avenger-0.8.5/util/clock_gettime.c0000644000175000017500000000325011221235216014021 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #ifndef HAVE_CLOCK_GETTIME #include int clock_gettime (int id, struct timespec *tp) { struct timeval tv; struct rusage ru; switch (id) { case CLOCK_REALTIME: if (gettimeofday (&tv, NULL) < 0) return -1; tp->tv_sec = tv.tv_sec; tp->tv_nsec = tv.tv_usec * 1000; return 0; case CLOCK_VIRTUAL: if (getrusage (RUSAGE_SELF, &ru) < 0) return -1; tp->tv_sec = ru.ru_utime.tv_sec; tp->tv_nsec = ru.ru_utime.tv_usec * 1000; return 0; case CLOCK_PROF: if (getrusage (RUSAGE_SELF, &ru) < 0) return -1; tp->tv_sec = (ru.ru_utime.tv_sec + ru.ru_stime.tv_sec); tp->tv_nsec = (ru.ru_utime.tv_usec + ru.ru_stime.tv_usec) * 1000; while (tp->tv_nsec > 1000000000) { tp->tv_sec++; tp->tv_nsec -= 1000000000; } return 0; default: errno = EINVAL; return -1; } } #endif /* !HAVE_CLOCK_GETTIME */ avenger-0.8.5/util/omacutil.c0000644000175000017500000002643111221235216013033 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include "getopt_long.h" char *progname; long opt_date; char *opt_pwfile; char *opt_expire; char *opt_aux; char *opt_sender; char *opt_from; char *opt_fromexp; int opt_verbose = 0; struct addrinfo { u_int32_t time; /* Expiration time */ unsigned nonce; /* 24-bit nonce */ u_char reserved : 1; u_char hasaux : 1; /* last 8 bytes hash of aux string */ u_char duration : 6; /* ceil (log_2 (seconds valid)) */ char aux[8]; /* must be zero or hash of aux string */ }; struct binaddr { char time[4]; /* message timestamp */ char nonce[3]; /* nonce */ char rhd; /* reserved/hasaux/duration*/ char aux[8]; /* zero or hash of aux string */ }; static inline void put3b (void *_dp, u_int32_t val) { unsigned char *dp = (unsigned char *) (_dp); dp[0] = val >> 16; dp[1] = val >> 8; dp[2] = val; } static inline u_int32_t get3b (const void *_dp) { const unsigned char *dp = (const unsigned char *) (_dp); return dp[0] << 16 | dp[1] << 8 | dp[2]; } static void h2nai (struct binaddr *out, const struct addrinfo *in) { putint (out->time, in->time); put3b (out->nonce, in->nonce); out->rhd = in->duration; if (in->hasaux) { out->rhd |= 0x40; memcpy (out->aux, in->aux, sizeof (out->aux)); } else bzero (out->aux, sizeof (out->aux)); } static void n2hai (struct addrinfo *out, const struct binaddr *in) { out->time = getint (in->time); out->nonce = get3b (in->nonce); out->duration = in->rhd & 0x3f; out->hasaux = !!(in->rhd & 0x40); out->reserved = !!(in->rhd & 0x80); memcpy (out->aux, in->aux, sizeof (out->aux)); } char * getmacpw (FILE *pwfile) { static char hashbuf[20]; char pwbuf[300]; char *p; sha1_ctx sha; if (!fgets (pwbuf, sizeof (pwbuf), pwfile)) return NULL; p = strchr (pwbuf, '\n'); if (!p) { fprintf (stderr, "password file line too long\n"); exit (1); } *p = '\0'; sha1_init (&sha); sha1_update (&sha, pwbuf, p - pwbuf); sha1_final (&sha, (void *) hashbuf); bzero (pwbuf, sizeof (pwbuf)); return hashbuf; } void sha1_str (char *out, size_t outlen, const char *in) { sha1_ctx sha; char hashbuf[sha1_hashsize]; sha1_init (&sha); sha1_update (&sha, in, strlen (in)); sha1_final (&sha, (void *) hashbuf); memcpy (out, hashbuf, outlen < sizeof (hashbuf) ? outlen : sizeof (hashbuf)); } char * mkaddr (const char *pw, time_t exp, const char *aux) { struct addrinfo ai; struct binaddr bi; struct timespec ts; aes_ctx aes; char *asc; ai.time = exp; clock_gettime (CLOCK_REALTIME, &ts); ai.nonce = ts.tv_nsec >> 6; ai.reserved = 0; ai.hasaux = !!aux; if (exp > opt_date) { u_long dur = exp - opt_date; int logdur = 0; while (dur > 0) { logdur++; dur = dur >> 1; } ai.duration = logdur; } else ai.duration = 0; if (aux) sha1_str (ai.aux, sizeof (ai.aux), aux); h2nai (&bi, &ai); aes_setkey (&aes, pw, 16); aes_encrypt (&aes, &bi, &bi); asc = armor32 (&bi, 16); return asc; } void do_gen (const char *pw, time_t exp, const char *aux) { char *asc = mkaddr (pw, exp, aux); printf ("%s\n", asc); free (asc); } void do_check (FILE *pwfile, char *asc, const char *auxsrc) { char dbuf[16]; char *pw; aes_ctx aes; unsigned long now = opt_date; int bad; struct binaddr bi; struct addrinfo ai; char aux[sizeof (ai.aux)]; if (auxsrc) sha1_str (aux, sizeof (aux), auxsrc); else bzero (aux, sizeof (aux)); if (dearmor32len (asc) != sizeof (dbuf) || (size_t) dearmor32 (dbuf, asc) != strlen (asc)) { fprintf (stderr, "bad input format\n"); exit (1); } /* dearmor32 might ignore trailing bits, so double check we would * have produce this output. (This only matters for security if you * are imposing some sort of quote per token, in which case users * could generate more valid looking tokens by manipulating the last * character of the token.) */ pw = armor32 (dbuf, 16); bad = strcmp (pw, asc); free (pw); if (bad) { fprintf (stderr, "bad input format\n"); exit (1); } do { bad = 0; pw = getmacpw (pwfile); if (!pw) { fprintf (stderr, "bad mac\n"); exit (1); } aes_setkey (&aes, pw, 16); bzero (pw, 20); aes_decrypt (&aes, &bi, dbuf); n2hai (&ai, &bi); if (!auxsrc != !ai.hasaux) bad++; if (memcmp (aux, ai.aux, sizeof (aux))) bad++; if (opt_verbose) { printf ("Decrypted to:\n"); printf (" Time: %lu\n", (unsigned long) ai.time); printf (" Nonce: %u\n", ai.nonce); printf ("reserved: %d\n", (int) ai.reserved); printf (" hasaux: %d\n", (int) ai.hasaux); printf ("duration: %d\n", (int) ai.duration); printf (" aux: %s\n", bad ? "bad" : "ok"); } if (now > ai.time || (ai.time - now) >> ai.duration) bad++; } while (bad); bzero (&aes, sizeof (aes)); } char * firstpw (void) { char *ret; FILE *pwfile = fopen (opt_pwfile, "r"); if (!pwfile) { perror (opt_pwfile); return NULL; } ret = getmacpw (pwfile); fclose (pwfile); return ret; } char * mksender (long exp, const char *aux) { char *p, *q, *s, *sender; s = opt_sender; if (!s) s = getenv ("MACUTIL_SENDER"); if (!s) { fprintf (stderr, "%s: no MACUTIL_SENDER environment variable\n", progname); return NULL; } p = strchr (s, '@'); if (!p) p = s + strlen (s); for (q = p; *q != '*'; q--) if (q == s) { fprintf (stderr, "%s: MACUTIL_SENDER must contain '*'\n", progname); return NULL; } p = firstpw (); if (!p) return NULL; sender = mkaddr (p, exp, aux); bzero (p, 20); p = sender; sender = xmalloc ((q - s) + strlen (q) + strlen (p)); sprintf (sender, "%.*s%s%s", (int) (q - s), s, p, *q ? q + 1 : ""); free (p); return sender; } int do_sendmail (int argc, char **argv) { char *sendmail = getenv ("MACUTIL_SENDMAIL"); char *sender = NULL; char **av; long exp; exp = parse_expire (opt_expire, opt_date); if (exp != -1) sender = mksender (exp, opt_aux); av = xmalloc ((argc + 3) * sizeof (av[0])); av[0] = sendmail ? sendmail : "sendmail"; av[1] = "-f"; av[2] = sender; memcpy (av + 3, argv + 1, (argc - 1) * sizeof (av[0])); av[argc+2] = NULL; if (sender) execvp (av[0], av); else { av[2] = av[0]; execvp (av[0], av + 2); } perror (av[0]); exit (1); } static char * default_macpass (void) { char defsuf[] = "/.avenger/.macpass"; char *home = getenv ("HOME"); char *ret; if (!home) { fprintf (stderr, "no HOME environment variable set\n"); exit (1); } ret = xmalloc (strlen (home) + sizeof (defsuf)); sprintf (ret, "%s%s", home, defsuf); return ret; } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s --gen [options]\n", progname); fprintf (stderr, " %s --sender [options] address-template\n", progname); fprintf (stderr, " %s --check [options] nonce\n", progname); fprintf (stderr, " %s --sendmail [sendmail options]\n", progname); fprintf (stderr, "options are:\n" " --passfile=file File containing password(s)\n" " --expire=date Set expiration date with --gen\n" " --date=date Act as if current time were date\n"); exit (1); } int main (int argc, char **argv) { int mode = 0; int c; struct option o[] = { { "version", no_argument, NULL, 'v' }, { "check", no_argument, &mode, 'c' }, { "gen", no_argument, &mode, 'g' }, { "passfile", required_argument, NULL, 'p' }, { "expire", required_argument, NULL, 'e' }, { "date", required_argument, NULL, 'd' }, { "aux", required_argument, NULL, 'a' }, { "from", required_argument, NULL, 'f' }, { "sender", required_argument, NULL, 's' }, { "fromexp", required_argument, NULL, 'E' }, { "sendmail", no_argument, NULL, 'M' }, { NULL, 0, NULL, 0 } }; FILE *pwfile; opt_date = time (NULL); opt_expire = getenv ("MACUTIL_EXPIRE"); if (!opt_expire) opt_expire = "+21D"; opt_pwfile = getenv ("MACUTIL_PASSFILE"); if (!opt_pwfile) opt_pwfile = default_macpass (); progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; if (!strncmp (progname, "send", 4)) return do_sendmail (argc, argv); while ((c = getopt_long (argc, argv, "+Vcf:gp:s:", o, NULL)) != -1) switch (c) { case 0: break; case 'E': opt_fromexp = optarg; break; case 'M': return do_sendmail (argc - optind + 1, argv + optind - 1); case 'a': opt_aux = optarg; break; case 'v': version (progname, 1); break; case 'V': opt_verbose = 1; break; case 'd': opt_date = parse_expire (optarg, time (NULL)); break; case 'e': opt_expire = optarg; break; case 'p': opt_pwfile = optarg; break; case 'f': opt_from = optarg; break; case 's': opt_sender = optarg; break; case 'c': case 'g': mode = c; break; default: usage (); break; } argv += optind; argc -= optind; if (opt_sender) { if (mode == 'c') usage (); mode = 's'; } if (!mode && opt_from && (opt_sender = getenv ("MACUTIL_SENDER"))) mode = 's'; if (!mode || opt_date == -1) usage (); pwfile = fopen (opt_pwfile, "r"); if (!pwfile) { perror (opt_pwfile); exit (1); } switch (mode) { case 'g': { long exp = parse_expire (opt_expire, opt_date); char *pw = getmacpw (pwfile); if (argc || exp == -1) usage (); if (!pw) { fprintf (stderr, "%s: no passwords\n", opt_pwfile); exit (1); } do_gen (pw, exp, opt_aux); bzero (pw, 20); break; } case 'c': if (argc != 1) usage (); do_check (pwfile, argv[0], opt_aux); break; case 's': { char *from; long exp = parse_expire (opt_expire, opt_date); if (argc || exp == -1) usage (); from = mksender (exp, opt_aux); if (!from) exit (1); if (opt_from) { printf ("%s", opt_from); if (opt_fromexp || (opt_fromexp = getenv ("MACUTIL_FROMEXP"))) { time_t t = exp; char buf[80]; strftime (buf, sizeof (buf), "%d %b %Y", localtime (&t)); buf[sizeof (buf) - 1] = '\0'; printf (" (%s%s%s)", opt_fromexp, *opt_fromexp ? " " : "", buf); } printf (" <%s>\n", from); } else printf ("%s\n", from); exit (0); break; } default: usage (); break; } #if 0 hmac_sha1 (buf, argv[1], argv[2], strlen (argv[2])); for (i = 0; i < sizeof (buf); i++) printf ("%02x", buf[i]); printf ("\n"); #endif return 0; } avenger-0.8.5/util/flock.c0000644000175000017500000000334111221235216012307 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "sysconf.h" #ifndef HAVE_FLOCK /* This is a substitute definition for flock in terms of the POSIX * fcntl file locking. Note that the semantics are not the same. In * particular, POSIX fcntl locking has very stupid semantics where * closing any file descriptor for a file relinquishes all locks. * Thus, unrelated parts of your program can unintentionally nuke your * locks. */ int flock (int fd, int options) { static const char optok[16] = { 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, }; int ret; struct flock lf; if ((u_int) options > 8 || !optok[options]) { errno = EINVAL; return -1; } bzero (&lf, sizeof (lf)); if (options & LOCK_UN) { lf.l_type = F_UNLCK; ret = fcntl (fd, F_SETLK, &lf); } else { int cmd = (options & LOCK_NB) ? F_SETLK : F_SETLKW; lf.l_type = (options & LOCK_EX) ? F_WRLCK : F_RDLCK; ret = fcntl (fd, cmd, &lf); } return -(ret == -1); } #endif /* !HAVE_FLOCK */ avenger-0.8.5/util/dbutil.c0000644000175000017500000001751011633212740012503 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include "dbexp.h" #include #include "getopt_long.h" char *progname; dbenv *env; int opt_sync = 1; static char * _do_dump_time (time_t t) { static char buf[80]; int n; if ((u_int32_t) t == 0xffffffff) return ""; n = strftime (buf, sizeof (buf) - 1, " (%a %b %e %Y %H:%M:%S)", localtime (&t)); if (n) return buf; else return ""; } int do_dump (const char *db) { dbexp *dbx; DBC *c; int err; DBT k, v; int ret = 0; if (!(dbx = dbexp_alloc (env, db, 1))) return 2; err = dbx->db->cursor (dbx->db, NULL, &c, 0); if (err) { fprintf (stderr, "%s; %s\n", db, db_strerror (err)); dbexp_free (dbx, 0); return 2; } bzero (&k, sizeof (k)); bzero (&v, sizeof (v)); err = c->c_get (c, &k, &v, DB_FIRST); while (!err) { if (v.size >= 4) { time_t t = getint (v.data); printf ("%.*s %.*s%s\n", (int) k.size, (char *) k.data, (int) v.size - 4, (char *) v.data + 4, _do_dump_time (t)); } err = c->c_get (c, &k, &v, DB_NEXT); } if (err && err != DB_NOTFOUND) { fprintf (stderr, "%s; %s\n", db, db_strerror (err)); ret = 2; } c->c_close (c); dbexp_free (dbx, 0); return ret; } int do_update (const char *db, const char *key, const char *val, int opt_n, const char *opt_expire) { dbexp *dbx; DBT k, v; int ret = 0; int err; long exp; if (!(dbx = dbexp_alloc (env, db, 0)) || dbexp_clean (dbx)) return 2; bzero (&k, sizeof (k)); k.data = (void *) key; k.size = strlen (key); bzero (&v, sizeof (v)); v.size = 4 + strlen (val); v.data = xmalloc (v.size + 1); if (opt_expire && (exp = parse_expire (opt_expire, time (NULL))) != -1) putint (v.data, exp); else putint (v.data, 0xffffffff); strcpy ((char *) v.data + 4, val); err = dbx->db->put (dbx->db, NULL, &k, &v, dbx->dbe->txnflag | (opt_n ? DB_NOOVERWRITE : 0)); if (err == DB_KEYEXIST) ret = 1; else if (err) { fprintf (stderr, "%s; %s\n", db, db_strerror (err)); ret = 2; } err = dbexp_free (dbx, opt_sync); if (err && ret < 2) { fprintf (stderr, "%s; %s\n", db, db_strerror (err)); ret = 2; } return ret; } int do_query (const char *db, const char *key, int opt_t, const char *opt_expire) { dbexp *dbx; DBT k, v; int err; u_int32_t now = time (NULL); if (!(dbx = dbexp_alloc (env, db, !opt_expire)) || (opt_expire && dbexp_clean (dbx))) return 2; bzero (&k, sizeof (k)); k.data = (void *) key; k.size = strlen (key); bzero (&v, sizeof (v)); err = dbx->db->get (dbx->db, NULL, &k, &v, 0); if (err == DB_NOTFOUND) { dbexp_free (dbx, 0); return 1; } else if (err) { fprintf (stderr, "%s: %s\n", db, db_strerror (err)); dbexp_free (dbx, 0); return 2; } else if (v.size < 4) { fprintf (stderr, "%s: record too short\n", db); dbexp_free (dbx, 0); return 2; } if (now > getint (v.data)) { dbexp_free (dbx, opt_expire && opt_sync); return 1; } if (opt_t) printf ("%lu\n", (unsigned long) getint (v.data)); else printf ("%.*s\n", (int) (v.size - 4), (char *) v.data + 4); if (opt_expire) { long exp = parse_expire (opt_expire, time (NULL)); if (exp != -1) { putint (v.data, exp); v.size = 4; v.dlen = 4; v.flags |= DB_DBT_PARTIAL; err = dbx->db->put (dbx->db, NULL, &k, &v, dbx->dbe->txnflag); if (err) fprintf (stderr, "%s; %s\n", dbx->path, db_strerror (err)); } else opt_expire = NULL; } err = dbexp_free (dbx, opt_expire && opt_sync); if (err) { fprintf (stderr, "%s; %s\n", dbx->path, db_strerror (err)); return 2; } return 0; } int do_delete (const char *db, const char *key) { dbexp *dbx; DBT k; int ret = 0; int err; if (!(dbx = dbexp_alloc (env, db, 0)) || dbexp_clean (dbx)) return 2; bzero (&k, sizeof (k)); k.data = (void *) key; k.size = strlen (key); err = dbx->db->del (dbx->db, NULL, &k, dbx->dbe->txnflag); if (err == DB_NOTFOUND) ret = 1; else if (err) { fprintf (stderr, "%s; %s\n", db, db_strerror (err)); ret = 2; } err = dbexp_free (dbx, opt_sync); if (err) return 2; return ret; } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s options {-d | --dump} db\n", progname); fprintf (stderr, " %s options {-q | --query}" " [-t] db key\n", progname); fprintf (stderr, " %s options {-u | --update}" " [-n] db key [value]\n", progname); fprintf (stderr, " %s options {-x | --delete} db key\n", progname); fprintf (stderr, " %s -t\n", progname); fprintf (stderr, "options are:\n" " --dbhome=DB_HOME Specify directory for DB log files\n" " --expire=date Specify timestamp for expiration\n"); exit (1); } #define opt_dbenv 0x101 int main (int argc, char **argv) { int mode = 0; struct option o[] = { { "nosync", no_argument, NULL, 'N' }, { "version", no_argument, &mode, 'v' }, { "dbhome", required_argument, NULL, opt_dbenv }, { "dump", no_argument, NULL, 'd' }, { "query", no_argument, NULL, 'q' }, { "update", no_argument, NULL, 'u' }, { "delete", no_argument, NULL, 'x' }, { "expire", required_argument, NULL, 'e' }, { NULL, 0, NULL, 0 } }; int c; int opt_n = 0, opt_t = 0; int ret = 0; char *opt_expire = NULL; char *dbenvdir = getenv ("DB_HOME"); progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; while ((c = getopt_long (argc, argv, "Ndquxnte", o, NULL)) != -1) switch (c) { case 0: break; case 'N': opt_sync = 0; break; case 'e': opt_expire = optarg; break; case 'n': opt_n = 1; break; case 't': opt_t = 1; break; case 'd': case 'q': case 'u': case 'x': if (mode) usage (); mode = c; break; case opt_dbenv: dbenvdir = optarg; break; default: usage (); } if (mode == 'v') version (progname, 1); if (opt_n && mode != 'u') usage (); if (opt_t && !mode) { if (optind + 1 == argc) { long exp = parse_expire (argv[optind], time (NULL)); if (exp == -1) exit (2); printf ("%lu\n", exp); } else if (optind == argc) printf ("%lu\n", (unsigned long) time (NULL)); else usage (); exit (0); } if (opt_t && mode != 'q') usage (); env = dbenv_alloc (dbenvdir); if (!env) exit (2); switch (mode) { case 'd': if (argc != optind + 1) usage (); ret = do_dump (argv[optind]); break; case 'q': if (argc != optind + 2) usage (); ret = do_query (argv[optind], argv[optind+1], opt_t, opt_expire); break; case 'u': if (argc < optind + 2 || argc > optind + 3) usage (); ret = do_update (argv[optind], argv[optind+1], argc < optind + 3 ? "" : argv[optind+2], opt_n, opt_expire); break; case 'x': if (argc != optind + 2) usage (); ret = do_delete (argv[optind], argv[optind+1]); break; default: usage (); } dbenv_free (env); return ret; } avenger-0.8.5/util/edinplace.c0000644000175000017500000002156711332761414013156 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include #include #include #include #include #include "getopt_long.h" int garbage; #ifdef NEED_PREAD_DECL ssize_t pread(int fd, void *buf, size_t size, off_t offset); #endif /* NEED_PREAD_DECL */ #ifdef NEED_PWRITE_DECL ssize_t pwrite(int fd, const void *buf, size_t size, off_t offset); #endif /* NEED_PWRITE_DECL */ char *progname; struct filter_state { int file; int filter; char file_eof; char filter_eof; char filter_weof; off_t read_offset; off_t write_offset; size_t read_pos; size_t read_lim; size_t write_buf_size; size_t write_pos; size_t write_lim; char read_buf[8192]; char *write_buf; }; typedef struct filter_state filter_state; pid_t filter_pid; int error_exit = 1; static void close_on_exec (int s) { if (fcntl (s, F_SETFD, 1) < 0) { perror ("F_SETFD"); exit (error_exit); } } static int make_async (int s) { int n; if ((n = fcntl (s, F_GETFL)) < 0 || fcntl (s, F_SETFL, n | O_NONBLOCK) < 0) return -1; return 0; } int spawnit (int argc, char **argv) { char **av = xmalloc ((argc + 1) * sizeof (*av)); int socks[2]; int errpipe[2]; memcpy (av, argv, argc * sizeof (*av)); av[argc] = NULL; if (socketpair (AF_UNIX, SOCK_STREAM, 0, socks) < 0) { perror ("socketpair"); exit (error_exit); } close_on_exec (socks[0]); close_on_exec (socks[1]); make_async (socks[0]); if (pipe (errpipe) < 0) { perror ("socketpair"); exit (error_exit); } close_on_exec (errpipe[0]); close_on_exec (errpipe[1]); filter_pid = fork (); if (filter_pid < 0) { perror ("fork"); exit (error_exit); } if (!filter_pid) { dup2 (socks[1], 0); dup2 (socks[1], 1); execvp (av[0], av); perror (av[0]); garbage = write (errpipe[1], &errno, sizeof (errno)); _exit (1); } close (socks[1]); close (errpipe[1]); if (read (errpipe[0], &errno, sizeof (errno)) > 0) exit (error_exit); close (errpipe[0]); return socks[0]; } static void maybe_write_to_file (filter_state *sp) { ssize_t n; n = sp->write_lim - sp->write_pos; if (!sp->file_eof) { off_t d = sp->read_offset - sp->write_offset; if (n > d) n = d; } if (n > 0) { n = pwrite (sp->file, sp->write_buf + sp->write_pos, n, sp->write_offset); if (n < 0) { perror ("file"); exit (error_exit); sp->write_offset += n; sp->write_pos += n; } sp->write_pos += n; sp->write_offset += n; } } void tofilter (filter_state *sp) { int n; if (!sp->file_eof && sp->read_pos == sp->read_lim) { sp->read_pos = sp->read_lim = 0; n = pread (sp->file, sp->read_buf, sizeof (sp->read_buf), sp->read_offset); if (n > 0) { sp->read_lim = n; sp->read_offset += n; } else { sp->file_eof = 1; sp->read_offset = -1; } maybe_write_to_file (sp); } if (sp->read_lim > sp->read_pos) { n = write (sp->filter, sp->read_buf + sp->read_pos, sp->read_lim - sp->read_pos); if (n < 0 && errno != EAGAIN) { if (errno != EPIPE) perror ("filter"); sp->filter_weof = 1; return; } else if (n >= 0) sp->read_pos += n; } if (sp->file_eof && sp->read_pos == sp->read_lim) { shutdown (sp->filter, 1); sp->filter_weof = 1; } } void fromfilter (filter_state *sp) { ssize_t n; if (sp->filter_eof) return; if (sp->write_pos == sp->write_lim) sp->write_pos = sp->write_lim = 0; else if (sp->write_pos > 0) { memmove (sp->write_buf, sp->write_buf + sp->write_pos, sp->write_lim - sp->write_pos); sp->write_lim -= sp->write_pos; sp->write_pos = 0; } if (sp->write_lim == sp->write_buf_size) { sp->write_buf_size *= 2; sp->write_buf = realloc (sp->write_buf, sp->write_buf_size); if (!sp->write_buf) { fprintf (stderr, "out of memory\n"); abort (); } } n = read (sp->filter, sp->write_buf + sp->write_lim, sp->write_buf_size - sp->write_lim); if (n > 0) { sp->write_lim += n; maybe_write_to_file (sp); } else if (!n || errno != EAGAIN) sp->filter_eof = 1; } void dofilter (int file, int filter, off_t start_offset) { int n; filter_state state; fd_set rfds, wfds; bzero (&state, sizeof (state)); state.read_offset = state.write_offset = start_offset; state.file = file; state.filter = filter; state.write_buf_size = 8192; state.write_buf = xmalloc (state.write_buf_size); FD_ZERO (&rfds); FD_ZERO (&wfds); for (;;) { if (state.filter_eof) FD_CLR (state.filter, &rfds); else FD_SET (state.filter, &rfds); if (state.filter_weof) FD_CLR (state.filter, &wfds); else FD_SET (state.filter, &wfds); n = select (1 + (state.filter > state.file ? state.filter : state.file), &rfds, &wfds, NULL, NULL); if (n < 0) { perror ("select"); exit (error_exit); } if (FD_ISSET (state.filter, &wfds)) tofilter (&state); else if (FD_ISSET (state.filter, &rfds)) fromfilter (&state); if (state.filter_eof && state.filter_weof) { int status; if (ftruncate (state.file, state.write_offset) == -1) { perror ("ftruncate"); exit (error_exit); } lseek (state.file, 0, SEEK_SET); close (state.file); close (state.filter); if (waitpid (filter_pid, &status, 0) < 0) { perror ("waitpid"); exit (error_exit); } if (WIFEXITED (status)) exit (WEXITSTATUS (status)); if (WIFSIGNALED (status)) { struct rlimit rl; bzero (&rl, sizeof (rl)); setrlimit (RLIMIT_CORE, &rl); raise (WTERMSIG (status)); } exit (error_exit); } } } /* Assumes fd is already at offset zero; leaves offset at arbitrary * location. */ off_t skipfrom (int fd) { char buf[1024], *e; int n; off_t pos = 0; while (pos < 5) { n = read (fd, buf + pos, sizeof (buf) - pos); if (n == 0) return 0; if (n < 0) return -1; pos += n; } if (strncmp (buf, "From ", 5)) return 0; n = pos; pos = 0; for (;;) { if ((e = memchr (buf, '\n', n))) return pos + (e - buf) + 1; pos += n; n = read (fd, buf, sizeof (buf)); if (n < 0) return -1; if (n == 0) return pos; } } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s [--skipfrom] [-x err_exit] [[-f file]" " filter [arg ...]]\n", progname); exit (error_exit); } int main (int argc, char **argv) { int c; struct option o[] = { { "skipfrom", no_argument, NULL, 'S' }, { "file", required_argument, NULL, 'f' }, { "error", required_argument, NULL, 'x' }, { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; char *opt_file = NULL; int opt_skipfrom = 0; int fd = 0; int fil = -1; off_t start_offset = 0; progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; while ((c = getopt_long (argc, argv, "+f:x:", o, NULL)) != -1) switch (c) { case 'S': opt_skipfrom = 1; break; case 'f': if (opt_file) usage (); opt_file = optarg; break; case 'x': error_exit = atoi (optarg); if (error_exit <= 0 || error_exit > 255) usage (); break; case 'v': version (progname, 1); break; default: usage (); break; } argv += optind; argc -= optind; if (opt_file) { if (!argc) usage (); fd = open (opt_file, O_RDWR, 0); if (fd < 0) { perror (opt_file); exit (error_exit); } } if (lseek (fd, 0, SEEK_SET) == -1) { fprintf (stderr, "cannot seek in input file (%s)\n", strerror (errno)); exit (error_exit); } if (opt_skipfrom) { start_offset = skipfrom (fd); if (start_offset == -1) { fprintf (stderr, "cannot read input file (%s)\n", strerror (errno)); exit (error_exit); } } if (!argc) { if (lseek (fd, start_offset, SEEK_SET) == -1) { fprintf (stderr, "cannot seek in input file (%s)\n", strerror (errno)); exit (error_exit); } exit (0); } fil = spawnit (argc, argv); signal (SIGPIPE, SIG_IGN); dofilter (fd, fil, start_offset); return 0; } avenger-0.8.5/util/vector.h0000644000175000017500000000407611221235216012526 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 _VECTOR_H_ #define _VECTOR_H_ 1 #define VECTOR(type) \ struct { \ int v_nalloc; \ int v_size; \ type *v_vec; \ } #define VECTOR_INIT(vp) \ do { \ (vp)->v_nalloc = (vp)->v_size = 0; \ (vp)->v_vec = NULL; \ } while (0) #define VECTOR_CLEAR(vp) free ((vp)->v_vec) #define VECTOR_GROW(vp) \ (void) ((vp)->v_size >= (vp)->v_nalloc \ && ((vp)->v_nalloc = ((vp)->v_nalloc ? (vp)->v_nalloc << 1 : 1), \ (vp)->v_vec = xrealloc ((vp)->v_vec, \ (vp)->v_nalloc * sizeof (*(vp)->v_vec)))) #define VECTOR_PUSH(vp, elm) \ do { \ VECTOR_GROW (vp); \ (vp)->v_vec[(vp)->v_size++] = (elm); \ } while (0) #define VECTOR_POP(vp) \ ((vp)->v_size ? &(vp)->v_vec[--(vp)->v_size] : NULL) #define VECTOR_NEXT(vp) \ (VECTOR_GROW(vp), &(vp)->v_vec[(vp)->v_size++]) #define VECTOR_LAST(vp) \ ((vp)->v_size ? &(vp)->v_vec[(vp)->v_size-1] : NULL) #define VECTOR_RESERVE(vp, n) \ do { \ if ((vp)->v_size + n > (vp)->v_nalloc) { \ do { \ && ((vp)->v_nalloc = (vp)->v_nalloc ? (vp)->v_nalloc << 1 : 1; \ } while ((vp)->v_size + n > (vp)->v_nalloc); \ (vp)->v_vec = xrealloc ((vp)->v_vec, \ (vp)->v_nalloc * sizeof (*(vp)->v_vec)); \ } \ } while (0) #endif /* !_VECTOR_H_ */ avenger-0.8.5/util/aes.c0000644000175000017500000015532011221235216011766 00000000000000/* $Id$ */ /* * * Copyright (C) 2002 David Mazieres (dm@uun.org) * * 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 * */ /* * This is a modified version the public-domain Rijndael * implementation by Vincent Rijmen, Antoon Bosselaers, and Paulo * Barreto used OpenBSD 3.2 kernel. * */ #include "avutil.h" #define FULL_UNROLL /* Te0[x] = S [x].[02, 01, 01, 03]; Te1[x] = S [x].[03, 02, 01, 01]; Te2[x] = S [x].[01, 03, 02, 01]; Te3[x] = S [x].[01, 01, 03, 02]; Te4[x] = S [x].[01, 01, 01, 01]; Td0[x] = Si[x].[0e, 09, 0d, 0b]; Td1[x] = Si[x].[0b, 0e, 09, 0d]; Td2[x] = Si[x].[0d, 0b, 0e, 09]; Td3[x] = Si[x].[09, 0d, 0b, 0e]; Td4[x] = Si[x].[01, 01, 01, 01]; */ static const u_int32_t Te0[256] = { 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU, 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U, 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU, 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU, 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U, 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU, 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU, 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U, 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU, 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU, 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U, 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU, 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU, 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU, 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU, 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU, 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U, 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU, 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU, 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU, 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU, 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U, 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U, 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U, 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U, 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU, 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U, 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U, 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU, 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU, 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U, 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U, 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U, 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU, 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U, 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU, 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U, 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU, 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U, 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U, 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU, 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U, 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U, 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U, 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U, 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U, 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U, 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U, 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U, 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU, 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U, 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U, 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U, 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U, 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U, 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U, 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU, 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U, 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U, 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U, 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU, }; static const u_int32_t Te1[256] = { 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU, 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U, 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU, 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U, 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU, 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U, 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU, 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U, 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U, 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU, 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U, 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U, 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U, 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU, 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U, 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U, 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU, 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U, 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U, 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U, 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU, 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU, 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U, 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU, 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU, 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U, 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU, 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U, 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU, 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U, 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U, 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U, 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU, 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U, 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU, 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U, 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU, 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U, 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U, 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU, 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU, 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU, 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U, 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U, 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU, 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U, 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU, 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U, 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU, 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U, 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU, 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU, 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U, 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU, 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U, 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU, 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U, 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U, 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U, 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU, 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU, 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U, 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU, 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U, }; static const u_int32_t Te2[256] = { 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU, 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U, 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU, 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U, 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU, 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U, 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU, 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U, 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U, 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU, 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U, 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U, 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U, 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU, 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U, 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U, 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU, 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U, 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U, 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U, 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU, 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU, 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U, 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU, 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU, 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U, 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU, 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U, 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU, 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U, 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U, 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U, 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU, 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U, 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU, 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U, 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU, 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U, 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U, 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU, 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU, 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU, 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U, 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U, 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU, 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U, 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU, 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U, 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU, 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U, 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU, 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU, 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U, 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU, 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U, 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU, 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U, 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U, 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U, 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU, 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU, 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U, 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU, 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U, }; static const u_int32_t Te3[256] = { 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U, 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U, 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U, 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU, 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU, 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU, 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U, 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU, 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU, 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U, 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U, 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU, 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU, 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU, 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU, 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU, 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U, 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU, 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU, 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U, 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U, 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U, 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U, 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U, 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU, 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U, 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU, 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU, 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U, 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U, 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U, 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU, 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U, 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU, 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU, 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U, 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U, 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU, 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U, 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU, 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U, 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U, 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U, 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U, 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU, 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U, 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU, 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U, 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU, 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U, 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU, 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU, 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU, 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU, 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U, 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U, 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U, 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U, 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U, 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U, 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU, 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U, 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU, 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU, }; static const u_int32_t Te4[256] = { 0x63636363U, 0x7c7c7c7cU, 0x77777777U, 0x7b7b7b7bU, 0xf2f2f2f2U, 0x6b6b6b6bU, 0x6f6f6f6fU, 0xc5c5c5c5U, 0x30303030U, 0x01010101U, 0x67676767U, 0x2b2b2b2bU, 0xfefefefeU, 0xd7d7d7d7U, 0xababababU, 0x76767676U, 0xcacacacaU, 0x82828282U, 0xc9c9c9c9U, 0x7d7d7d7dU, 0xfafafafaU, 0x59595959U, 0x47474747U, 0xf0f0f0f0U, 0xadadadadU, 0xd4d4d4d4U, 0xa2a2a2a2U, 0xafafafafU, 0x9c9c9c9cU, 0xa4a4a4a4U, 0x72727272U, 0xc0c0c0c0U, 0xb7b7b7b7U, 0xfdfdfdfdU, 0x93939393U, 0x26262626U, 0x36363636U, 0x3f3f3f3fU, 0xf7f7f7f7U, 0xccccccccU, 0x34343434U, 0xa5a5a5a5U, 0xe5e5e5e5U, 0xf1f1f1f1U, 0x71717171U, 0xd8d8d8d8U, 0x31313131U, 0x15151515U, 0x04040404U, 0xc7c7c7c7U, 0x23232323U, 0xc3c3c3c3U, 0x18181818U, 0x96969696U, 0x05050505U, 0x9a9a9a9aU, 0x07070707U, 0x12121212U, 0x80808080U, 0xe2e2e2e2U, 0xebebebebU, 0x27272727U, 0xb2b2b2b2U, 0x75757575U, 0x09090909U, 0x83838383U, 0x2c2c2c2cU, 0x1a1a1a1aU, 0x1b1b1b1bU, 0x6e6e6e6eU, 0x5a5a5a5aU, 0xa0a0a0a0U, 0x52525252U, 0x3b3b3b3bU, 0xd6d6d6d6U, 0xb3b3b3b3U, 0x29292929U, 0xe3e3e3e3U, 0x2f2f2f2fU, 0x84848484U, 0x53535353U, 0xd1d1d1d1U, 0x00000000U, 0xededededU, 0x20202020U, 0xfcfcfcfcU, 0xb1b1b1b1U, 0x5b5b5b5bU, 0x6a6a6a6aU, 0xcbcbcbcbU, 0xbebebebeU, 0x39393939U, 0x4a4a4a4aU, 0x4c4c4c4cU, 0x58585858U, 0xcfcfcfcfU, 0xd0d0d0d0U, 0xefefefefU, 0xaaaaaaaaU, 0xfbfbfbfbU, 0x43434343U, 0x4d4d4d4dU, 0x33333333U, 0x85858585U, 0x45454545U, 0xf9f9f9f9U, 0x02020202U, 0x7f7f7f7fU, 0x50505050U, 0x3c3c3c3cU, 0x9f9f9f9fU, 0xa8a8a8a8U, 0x51515151U, 0xa3a3a3a3U, 0x40404040U, 0x8f8f8f8fU, 0x92929292U, 0x9d9d9d9dU, 0x38383838U, 0xf5f5f5f5U, 0xbcbcbcbcU, 0xb6b6b6b6U, 0xdadadadaU, 0x21212121U, 0x10101010U, 0xffffffffU, 0xf3f3f3f3U, 0xd2d2d2d2U, 0xcdcdcdcdU, 0x0c0c0c0cU, 0x13131313U, 0xececececU, 0x5f5f5f5fU, 0x97979797U, 0x44444444U, 0x17171717U, 0xc4c4c4c4U, 0xa7a7a7a7U, 0x7e7e7e7eU, 0x3d3d3d3dU, 0x64646464U, 0x5d5d5d5dU, 0x19191919U, 0x73737373U, 0x60606060U, 0x81818181U, 0x4f4f4f4fU, 0xdcdcdcdcU, 0x22222222U, 0x2a2a2a2aU, 0x90909090U, 0x88888888U, 0x46464646U, 0xeeeeeeeeU, 0xb8b8b8b8U, 0x14141414U, 0xdedededeU, 0x5e5e5e5eU, 0x0b0b0b0bU, 0xdbdbdbdbU, 0xe0e0e0e0U, 0x32323232U, 0x3a3a3a3aU, 0x0a0a0a0aU, 0x49494949U, 0x06060606U, 0x24242424U, 0x5c5c5c5cU, 0xc2c2c2c2U, 0xd3d3d3d3U, 0xacacacacU, 0x62626262U, 0x91919191U, 0x95959595U, 0xe4e4e4e4U, 0x79797979U, 0xe7e7e7e7U, 0xc8c8c8c8U, 0x37373737U, 0x6d6d6d6dU, 0x8d8d8d8dU, 0xd5d5d5d5U, 0x4e4e4e4eU, 0xa9a9a9a9U, 0x6c6c6c6cU, 0x56565656U, 0xf4f4f4f4U, 0xeaeaeaeaU, 0x65656565U, 0x7a7a7a7aU, 0xaeaeaeaeU, 0x08080808U, 0xbabababaU, 0x78787878U, 0x25252525U, 0x2e2e2e2eU, 0x1c1c1c1cU, 0xa6a6a6a6U, 0xb4b4b4b4U, 0xc6c6c6c6U, 0xe8e8e8e8U, 0xddddddddU, 0x74747474U, 0x1f1f1f1fU, 0x4b4b4b4bU, 0xbdbdbdbdU, 0x8b8b8b8bU, 0x8a8a8a8aU, 0x70707070U, 0x3e3e3e3eU, 0xb5b5b5b5U, 0x66666666U, 0x48484848U, 0x03030303U, 0xf6f6f6f6U, 0x0e0e0e0eU, 0x61616161U, 0x35353535U, 0x57575757U, 0xb9b9b9b9U, 0x86868686U, 0xc1c1c1c1U, 0x1d1d1d1dU, 0x9e9e9e9eU, 0xe1e1e1e1U, 0xf8f8f8f8U, 0x98989898U, 0x11111111U, 0x69696969U, 0xd9d9d9d9U, 0x8e8e8e8eU, 0x94949494U, 0x9b9b9b9bU, 0x1e1e1e1eU, 0x87878787U, 0xe9e9e9e9U, 0xcecececeU, 0x55555555U, 0x28282828U, 0xdfdfdfdfU, 0x8c8c8c8cU, 0xa1a1a1a1U, 0x89898989U, 0x0d0d0d0dU, 0xbfbfbfbfU, 0xe6e6e6e6U, 0x42424242U, 0x68686868U, 0x41414141U, 0x99999999U, 0x2d2d2d2dU, 0x0f0f0f0fU, 0xb0b0b0b0U, 0x54545454U, 0xbbbbbbbbU, 0x16161616U, }; static const u_int32_t Td0[256] = { 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U, 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U, 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U, 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU, 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U, 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U, 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU, 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U, 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU, 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U, 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U, 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U, 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U, 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU, 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U, 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU, 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U, 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU, 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U, 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U, 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U, 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU, 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U, 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU, 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U, 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU, 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U, 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU, 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU, 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U, 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU, 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U, 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU, 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U, 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U, 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U, 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU, 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U, 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U, 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU, 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U, 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U, 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U, 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U, 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U, 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU, 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U, 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U, 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U, 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U, 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U, 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU, 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU, 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU, 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU, 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U, 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U, 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU, 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU, 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U, 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU, 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U, 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U, 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U, }; static const u_int32_t Td1[256] = { 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU, 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U, 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU, 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U, 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U, 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U, 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U, 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U, 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U, 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU, 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU, 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU, 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U, 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU, 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U, 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U, 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U, 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU, 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU, 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U, 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU, 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U, 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU, 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU, 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U, 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U, 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U, 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU, 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U, 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU, 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U, 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U, 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U, 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU, 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U, 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U, 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U, 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U, 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U, 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U, 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU, 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU, 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U, 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU, 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U, 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU, 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU, 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U, 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU, 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U, 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U, 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U, 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U, 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U, 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U, 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U, 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU, 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U, 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U, 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU, 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U, 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U, 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U, 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U, }; static const u_int32_t Td2[256] = { 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U, 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U, 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U, 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U, 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU, 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U, 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U, 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U, 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U, 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU, 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U, 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U, 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU, 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U, 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U, 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U, 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U, 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U, 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U, 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU, 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U, 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U, 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U, 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U, 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U, 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU, 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU, 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U, 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU, 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U, 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU, 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU, 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU, 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU, 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U, 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U, 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U, 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U, 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U, 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U, 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U, 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU, 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU, 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U, 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U, 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU, 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU, 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U, 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U, 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U, 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U, 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U, 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U, 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U, 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU, 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U, 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U, 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U, 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U, 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U, 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U, 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU, 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U, 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U, }; static const u_int32_t Td3[256] = { 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU, 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU, 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U, 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U, 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU, 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU, 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U, 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU, 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U, 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU, 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U, 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U, 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U, 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U, 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U, 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU, 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU, 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U, 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U, 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU, 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU, 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U, 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U, 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U, 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U, 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU, 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U, 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U, 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU, 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU, 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U, 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U, 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U, 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU, 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U, 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U, 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U, 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U, 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U, 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U, 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U, 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU, 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U, 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U, 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU, 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU, 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U, 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU, 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U, 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U, 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U, 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U, 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U, 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U, 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU, 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU, 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU, 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU, 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U, 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U, 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U, 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU, 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U, 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U, }; static const u_int32_t Td4[256] = { 0x52525252U, 0x09090909U, 0x6a6a6a6aU, 0xd5d5d5d5U, 0x30303030U, 0x36363636U, 0xa5a5a5a5U, 0x38383838U, 0xbfbfbfbfU, 0x40404040U, 0xa3a3a3a3U, 0x9e9e9e9eU, 0x81818181U, 0xf3f3f3f3U, 0xd7d7d7d7U, 0xfbfbfbfbU, 0x7c7c7c7cU, 0xe3e3e3e3U, 0x39393939U, 0x82828282U, 0x9b9b9b9bU, 0x2f2f2f2fU, 0xffffffffU, 0x87878787U, 0x34343434U, 0x8e8e8e8eU, 0x43434343U, 0x44444444U, 0xc4c4c4c4U, 0xdedededeU, 0xe9e9e9e9U, 0xcbcbcbcbU, 0x54545454U, 0x7b7b7b7bU, 0x94949494U, 0x32323232U, 0xa6a6a6a6U, 0xc2c2c2c2U, 0x23232323U, 0x3d3d3d3dU, 0xeeeeeeeeU, 0x4c4c4c4cU, 0x95959595U, 0x0b0b0b0bU, 0x42424242U, 0xfafafafaU, 0xc3c3c3c3U, 0x4e4e4e4eU, 0x08080808U, 0x2e2e2e2eU, 0xa1a1a1a1U, 0x66666666U, 0x28282828U, 0xd9d9d9d9U, 0x24242424U, 0xb2b2b2b2U, 0x76767676U, 0x5b5b5b5bU, 0xa2a2a2a2U, 0x49494949U, 0x6d6d6d6dU, 0x8b8b8b8bU, 0xd1d1d1d1U, 0x25252525U, 0x72727272U, 0xf8f8f8f8U, 0xf6f6f6f6U, 0x64646464U, 0x86868686U, 0x68686868U, 0x98989898U, 0x16161616U, 0xd4d4d4d4U, 0xa4a4a4a4U, 0x5c5c5c5cU, 0xccccccccU, 0x5d5d5d5dU, 0x65656565U, 0xb6b6b6b6U, 0x92929292U, 0x6c6c6c6cU, 0x70707070U, 0x48484848U, 0x50505050U, 0xfdfdfdfdU, 0xededededU, 0xb9b9b9b9U, 0xdadadadaU, 0x5e5e5e5eU, 0x15151515U, 0x46464646U, 0x57575757U, 0xa7a7a7a7U, 0x8d8d8d8dU, 0x9d9d9d9dU, 0x84848484U, 0x90909090U, 0xd8d8d8d8U, 0xababababU, 0x00000000U, 0x8c8c8c8cU, 0xbcbcbcbcU, 0xd3d3d3d3U, 0x0a0a0a0aU, 0xf7f7f7f7U, 0xe4e4e4e4U, 0x58585858U, 0x05050505U, 0xb8b8b8b8U, 0xb3b3b3b3U, 0x45454545U, 0x06060606U, 0xd0d0d0d0U, 0x2c2c2c2cU, 0x1e1e1e1eU, 0x8f8f8f8fU, 0xcacacacaU, 0x3f3f3f3fU, 0x0f0f0f0fU, 0x02020202U, 0xc1c1c1c1U, 0xafafafafU, 0xbdbdbdbdU, 0x03030303U, 0x01010101U, 0x13131313U, 0x8a8a8a8aU, 0x6b6b6b6bU, 0x3a3a3a3aU, 0x91919191U, 0x11111111U, 0x41414141U, 0x4f4f4f4fU, 0x67676767U, 0xdcdcdcdcU, 0xeaeaeaeaU, 0x97979797U, 0xf2f2f2f2U, 0xcfcfcfcfU, 0xcecececeU, 0xf0f0f0f0U, 0xb4b4b4b4U, 0xe6e6e6e6U, 0x73737373U, 0x96969696U, 0xacacacacU, 0x74747474U, 0x22222222U, 0xe7e7e7e7U, 0xadadadadU, 0x35353535U, 0x85858585U, 0xe2e2e2e2U, 0xf9f9f9f9U, 0x37373737U, 0xe8e8e8e8U, 0x1c1c1c1cU, 0x75757575U, 0xdfdfdfdfU, 0x6e6e6e6eU, 0x47474747U, 0xf1f1f1f1U, 0x1a1a1a1aU, 0x71717171U, 0x1d1d1d1dU, 0x29292929U, 0xc5c5c5c5U, 0x89898989U, 0x6f6f6f6fU, 0xb7b7b7b7U, 0x62626262U, 0x0e0e0e0eU, 0xaaaaaaaaU, 0x18181818U, 0xbebebebeU, 0x1b1b1b1bU, 0xfcfcfcfcU, 0x56565656U, 0x3e3e3e3eU, 0x4b4b4b4bU, 0xc6c6c6c6U, 0xd2d2d2d2U, 0x79797979U, 0x20202020U, 0x9a9a9a9aU, 0xdbdbdbdbU, 0xc0c0c0c0U, 0xfefefefeU, 0x78787878U, 0xcdcdcdcdU, 0x5a5a5a5aU, 0xf4f4f4f4U, 0x1f1f1f1fU, 0xddddddddU, 0xa8a8a8a8U, 0x33333333U, 0x88888888U, 0x07070707U, 0xc7c7c7c7U, 0x31313131U, 0xb1b1b1b1U, 0x12121212U, 0x10101010U, 0x59595959U, 0x27272727U, 0x80808080U, 0xececececU, 0x5f5f5f5fU, 0x60606060U, 0x51515151U, 0x7f7f7f7fU, 0xa9a9a9a9U, 0x19191919U, 0xb5b5b5b5U, 0x4a4a4a4aU, 0x0d0d0d0dU, 0x2d2d2d2dU, 0xe5e5e5e5U, 0x7a7a7a7aU, 0x9f9f9f9fU, 0x93939393U, 0xc9c9c9c9U, 0x9c9c9c9cU, 0xefefefefU, 0xa0a0a0a0U, 0xe0e0e0e0U, 0x3b3b3b3bU, 0x4d4d4d4dU, 0xaeaeaeaeU, 0x2a2a2a2aU, 0xf5f5f5f5U, 0xb0b0b0b0U, 0xc8c8c8c8U, 0xebebebebU, 0xbbbbbbbbU, 0x3c3c3c3cU, 0x83838383U, 0x53535353U, 0x99999999U, 0x61616161U, 0x17171717U, 0x2b2b2b2bU, 0x04040404U, 0x7e7e7e7eU, 0xbabababaU, 0x77777777U, 0xd6d6d6d6U, 0x26262626U, 0xe1e1e1e1U, 0x69696969U, 0x14141414U, 0x63636363U, 0x55555555U, 0x21212121U, 0x0c0c0c0cU, 0x7d7d7d7dU, }; static const u_int32_t rcon[] = { 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ }; static void aes_setkey_e (aes_ctx *aes, const char *key, u_int keylen) { int i; u_int32_t *rk = aes->e_key; rk[0] = getint (key); rk[1] = getint (key + 4); rk[2] = getint (key + 8); rk[3] = getint (key + 12); if (keylen == 16) { aes->nrounds = 10; for (i = 0;;) { u_int32_t temp = rk[3]; rk[4] = rk[0] ^ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ (Te4[(temp) & 0xff] & 0x0000ff00) ^ (Te4[(temp >> 24)] & 0x000000ff) ^ rcon[i]; rk[5] = rk[1] ^ rk[4]; rk[6] = rk[2] ^ rk[5]; rk[7] = rk[3] ^ rk[6]; if (++i == 10) return; rk += 4; } } rk[4] = getint (key + 16); rk[5] = getint (key + 20); if (keylen == 24) { aes->nrounds = 12; for (i = 0;;) { u_int32_t temp = rk[5]; rk[6] = rk[0] ^ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ (Te4[(temp) & 0xff] & 0x0000ff00) ^ (Te4[(temp >> 24)] & 0x000000ff) ^ rcon[i]; rk[7] = rk[1] ^ rk[6]; rk[8] = rk[2] ^ rk[7]; rk[9] = rk[3] ^ rk[8]; if (++i == 8) return; rk[10] = rk[4] ^ rk[9]; rk[11] = rk[5] ^ rk[10]; rk += 6; } } rk[6] = getint (key + 24); rk[7] = getint (key + 28); if (keylen == 32) { aes->nrounds = 14; for (i = 0;;) { u_int32_t temp = rk[7]; rk[8] = rk[0] ^ (Te4[(temp >> 16) & 0xff] & 0xff000000) ^ (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^ (Te4[(temp) & 0xff] & 0x0000ff00) ^ (Te4[(temp >> 24)] & 0x000000ff) ^ rcon[i]; rk[9] = rk[1] ^ rk[8]; rk[10] = rk[2] ^ rk[9]; rk[11] = rk[3] ^ rk[10]; if (++i == 7) return; temp = rk[11]; rk[12] = rk[4] ^ (Te4[(temp >> 24)] & 0xff000000) ^ (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(temp) & 0xff] & 0x000000ff); rk[13] = rk[5] ^ rk[12]; rk[14] = rk[6] ^ rk[13]; rk[15] = rk[7] ^ rk[14]; rk += 8; } } fprintf (stderr, "invalid AES key length %d (should be 16, 24, or 32).\n", keylen); abort (); } static void aes_setkey_d (aes_ctx *aes) { int i, j; u_int32_t *rk = aes->d_key; memcpy (rk, aes->e_key, sizeof (aes->e_key)); /* invert the order of the round keys: */ for (i = 0, j = 4 * aes->nrounds; i < j; i += 4, j -= 4) { u_int32_t temp = rk[i]; rk[i] = rk[j]; rk[j] = temp; temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; } /* apply the inverse MixColumn transform to all round keys but the * first and the last: */ for (i = 1; i < aes->nrounds; i++) { rk += 4; rk[0] = Td0[Te4[(rk[0] >> 24)] & 0xff] ^ Td1[Te4[(rk[0] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[0] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[0]) & 0xff] & 0xff]; rk[1] = Td0[Te4[(rk[1] >> 24)] & 0xff] ^ Td1[Te4[(rk[1] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[1] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[1]) & 0xff] & 0xff]; rk[2] = Td0[Te4[(rk[2] >> 24)] & 0xff] ^ Td1[Te4[(rk[2] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[2] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[2]) & 0xff] & 0xff]; rk[3] = Td0[Te4[(rk[3] >> 24)] & 0xff] ^ Td1[Te4[(rk[3] >> 16) & 0xff] & 0xff] ^ Td2[Te4[(rk[3] >> 8) & 0xff] & 0xff] ^ Td3[Te4[(rk[3]) & 0xff] & 0xff]; } } void aes_setkey (aes_ctx *aes, const void *key, u_int keylen) { aes_setkey_e (aes, key, keylen); aes_setkey_d (aes); } void aes_encrypt (const aes_ctx *aes, void *buf, const void *ibuf) { const char *pt = ibuf; char *ct = buf; u_int32_t s0, s1, s2, s3, t0, t1, t2, t3; const u_int32_t *rk = aes->e_key; /* * map byte array block to cipher state * and add initial round key: */ s0 = getint (pt) ^ rk[0]; s1 = getint (pt + 4) ^ rk[1]; s2 = getint (pt + 8) ^ rk[2]; s3 = getint (pt + 12) ^ rk[3]; #ifdef FULL_UNROLL /* round 1: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[4]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[5]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[6]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[7]; /* round 2: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[8]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[9]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11]; /* round 3: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15]; /* round 4: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19]; /* round 5: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23]; /* round 6: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27]; /* round 7: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31]; /* round 8: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35]; /* round 9: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39]; if (aes->nrounds > 10) { /* round 10: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43]; /* round 11: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47]; if (aes->nrounds > 12) { /* round 12: */ s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48]; s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49]; s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50]; s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51]; /* round 13: */ t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52]; t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53]; t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54]; t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55]; } } rk += aes->nrounds << 2; #else /* !FULL_UNROLL */ /* * nrounds - 1 full rounds: */ int r = aes->nrounds >> 1; for (;;) { t0 = Te0[(s0 >> 24)] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[(s3) & 0xff] ^ rk[4]; t1 = Te0[(s1 >> 24)] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[(s0) & 0xff] ^ rk[5]; t2 = Te0[(s2 >> 24)] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[(s1) & 0xff] ^ rk[6]; t3 = Te0[(s3 >> 24)] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[(s2) & 0xff] ^ rk[7]; rk += 8; if (--r == 0) break; s0 = Te0[(t0 >> 24)] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[(t3) & 0xff] ^ rk[0]; s1 = Te0[(t1 >> 24)] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[(t0) & 0xff] ^ rk[1]; s2 = Te0[(t2 >> 24)] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[(t1) & 0xff] ^ rk[2]; s3 = Te0[(t3 >> 24)] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[(t2) & 0xff] ^ rk[3]; } #endif /* !FULL_UNROLL */ /* * apply last round and * map cipher state to byte array block: */ s0 = (Te4[(t0 >> 24)] & 0xff000000) ^ (Te4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t3) & 0xff] & 0x000000ff) ^ rk[0]; putint (ct, s0); s1 = (Te4[(t1 >> 24)] & 0xff000000) ^ (Te4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t0) & 0xff] & 0x000000ff) ^ rk[1]; putint (ct + 4, s1); s2 = (Te4[(t2 >> 24)] & 0xff000000) ^ (Te4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t1) & 0xff] & 0x000000ff) ^ rk[2]; putint (ct + 8, s2); s3 = (Te4[(t3 >> 24)] & 0xff000000) ^ (Te4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ (Te4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ (Te4[(t2) & 0xff] & 0x000000ff) ^ rk[3]; putint (ct + 12, s3); } void aes_decrypt (const aes_ctx *aes, void *buf, const void *ibuf) { const char *ct = ibuf; char *pt = buf; u_int32_t s0, s1, s2, s3, t0, t1, t2, t3; const u_int32_t *rk = aes->d_key; /* * map byte array block to cipher state * and add initial round key: */ s0 = getint (ct) ^ rk[0]; s1 = getint (ct + 4) ^ rk[1]; s2 = getint (ct + 8) ^ rk[2]; s3 = getint (ct + 12) ^ rk[3]; #ifdef FULL_UNROLL /* round 1: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[4]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[5]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[6]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[7]; /* round 2: */ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[8]; s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[9]; s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10]; s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11]; /* round 3: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15]; /* round 4: */ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16]; s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17]; s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18]; s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19]; /* round 5: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23]; /* round 6: */ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24]; s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25]; s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26]; s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27]; /* round 7: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31]; /* round 8: */ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32]; s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33]; s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34]; s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35]; /* round 9: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39]; if (aes->nrounds > 10) { /* round 10: */ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40]; s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41]; s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42]; s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43]; /* round 11: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47]; if (aes->nrounds > 12) { /* round 12: */ s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48]; s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49]; s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50]; s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51]; /* round 13: */ t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52]; t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53]; t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54]; t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55]; } } rk += aes->nrounds << 2; #else /* !FULL_UNROLL */ /* * Nr - 1 full rounds: */ int r = aes->nrounds >> 1; for (;;) { t0 = Td0[(s0 >> 24)] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[(s1) & 0xff] ^ rk[4]; t1 = Td0[(s1 >> 24)] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[(s2) & 0xff] ^ rk[5]; t2 = Td0[(s2 >> 24)] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[(s3) & 0xff] ^ rk[6]; t3 = Td0[(s3 >> 24)] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[(s0) & 0xff] ^ rk[7]; rk += 8; if (--r == 0) break; s0 = Td0[(t0 >> 24)] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[(t1) & 0xff] ^ rk[0]; s1 = Td0[(t1 >> 24)] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[(t2) & 0xff] ^ rk[1]; s2 = Td0[(t2 >> 24)] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[(t3) & 0xff] ^ rk[2]; s3 = Td0[(t3 >> 24)] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[(t0) & 0xff] ^ rk[3]; } #endif /* !FULL_UNROLL */ /* * apply last round and * map cipher state to byte array block: */ s0 = (Td4[(t0 >> 24)] & 0xff000000) ^ (Td4[(t3 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t2 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t1) & 0xff] & 0x000000ff) ^ rk[0]; putint (pt, s0); s1 = (Td4[(t1 >> 24)] & 0xff000000) ^ (Td4[(t0 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t3 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t2) & 0xff] & 0x000000ff) ^ rk[1]; putint (pt + 4, s1); s2 = (Td4[(t2 >> 24)] & 0xff000000) ^ (Td4[(t1 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t0 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t3) & 0xff] & 0x000000ff) ^ rk[2]; putint (pt + 8, s2); s3 = (Td4[(t3 >> 24)] & 0xff000000) ^ (Td4[(t2 >> 16) & 0xff] & 0x00ff0000) ^ (Td4[(t1 >> 8) & 0xff] & 0x0000ff00) ^ (Td4[(t0) & 0xff] & 0x000000ff) ^ rk[3]; putint (pt + 12, s3); } avenger-0.8.5/util/mdblock.c0000644000175000017500000000567511221235216012640 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" enum { blocksize = 64 }; void mdblock_init (mdblock *mp, void (*consume) (mdblock *, const u_char block[blocksize])) { mp->count = 0; mp->consume = consume; } void mdblock_update (mdblock *mp, const void *bytes, size_t len) { const u_char *data = bytes; size_t i; u_int bcount = mp->count % blocksize; mp->count += len; if (bcount + len < blocksize) { memcpy (&mp->buffer[bcount], data, len); return; } /* copy first chunk into context, do the rest (if any) */ /* directly from data array */ if (bcount) { int j = blocksize - bcount; memcpy (&mp->buffer[bcount], data, j); mp->consume (mp, mp->buffer); i = j; len -= j; } else i = 0; while (len >= blocksize) { mp->consume (mp, &data[i]); i += blocksize; len -= blocksize; } memcpy (mp->buffer, &data[i], len); } void mdblock_finish (mdblock *mp, int bigendian) { u_char *dp; u_char *end; u_int bcount = mp->count % blocksize; u_int64_t cnt; if (bcount > blocksize - 9) { /* need to split padding bit and count */ u_char tmp[blocksize]; bzero (tmp, blocksize - bcount); /* add padding bit */ tmp[0] = 0x80; mdblock_update (mp, tmp, blocksize - bcount); /* don't count padding in length of string */ mp->count -= blocksize - bcount; dp = mp->buffer; } else { dp = &mp->buffer[bcount]; *dp++ = 0x80; } end = &mp->buffer[blocksize - 8]; while (dp < end) *dp++ = 0; cnt = mp->count <<= 3; /* make bytecount bitcount */ if (bigendian) { *dp++ = (cnt >> 56) & 0xff; *dp++ = (cnt >> 48) & 0xff; *dp++ = (cnt >> 40) & 0xff; *dp++ = (cnt >> 32) & 0xff; *dp++ = (cnt >> 24) & 0xff; *dp++ = (cnt >> 16) & 0xff; *dp++ = (cnt >> 8) & 0xff; *dp = (cnt >> 0) & 0xff; } else { *dp++ = (cnt >> 0) & 0xff; *dp++ = (cnt >> 8) & 0xff; *dp++ = (cnt >> 16) & 0xff; *dp++ = (cnt >> 24) & 0xff; *dp++ = (cnt >> 32) & 0xff; *dp++ = (cnt >> 40) & 0xff; *dp++ = (cnt >> 48) & 0xff; *dp = (cnt >> 56) & 0xff; } mp->consume (mp, mp->buffer); /* Wipe variables */ mp->consume = NULL; mp->count = 0; bzero (mp->buffer, sizeof (mp->buffer)); } avenger-0.8.5/util/match.c0000644000175000017500000002046111221235216012307 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include #include #include "vector.h" #include "getopt_long.h" typedef VECTOR(char *) strvec_t; #define MATCH_RIGHT 0x1 #define MATCH_SLASH 0x2 #define MATCH_NOCASE 0x4 #define MATCH_PAREN 0x8 #define MATCH_RECURSING 0x100 char *progname; int opt_fail = 67; void strvec_free (strvec_t *sv) { int i; for (i = 0; i < sv->v_size; i++) free (sv->v_vec[i]); VECTOR_CLEAR (sv); VECTOR_INIT (sv); } static int match_class (const char **patp, char c, int flags) { const char *pat; int first = 1; int not = 0; int hit = 0; assert (**patp == '['); for (pat = *patp + 1;; pat++) { if (!*pat) { if (c != '[') return 0; (*patp)++; return 1; } if (*pat == '!' && first && !not) { not = 1; continue; } if (*pat == ']' && !first) { if (hit != not) *patp = pat + 1; return hit != not; } if (*pat == '\\' && pat[1]) pat++; if (pat[1] == '-' && pat[2] && pat[2] != ']') { const char *next = pat + 2; if (*next == '\\' && next[1]) next++; if (flags & MATCH_NOCASE) { if ((*pat <= tolower (c) && tolower (c) <= *next) || (*pat <= toupper (c) && toupper (c) <= *next)) hit = 1; } else if (*pat <= c && c <= *next) hit = 1; pat = next; } else if (flags & MATCH_NOCASE) { if (tolower (*pat) == tolower (c)) hit = 1; } else if (*pat == c) hit = 1; first = 0; } } struct match_state { const char *pat; const char *s; }; int match (strvec_t *mv, const char *pat, const char *s, int flags, struct match_state *msp) { for (;;) { switch (*pat) { case '\0': if (msp) fprintf (stderr, "%s: unmatched '(' in pattern\n", progname); return !*s; case '(': if (!(flags & MATCH_PAREN)) goto do_default; else if (mv) { struct match_state ms; size_t mn = mv->v_size; bzero (&ms, sizeof (ms)); VECTOR_PUSH (mv, NULL); if (!match (mv, pat + 1, s, flags | MATCH_RECURSING, &ms) || !ms.s) { VECTOR_POP (mv); return 0; } mv->v_vec[mn] = xmalloc (ms.s - s + 1); memcpy (mv->v_vec[mn], s, ms.s - s); mv->v_vec[mn][ms.s - s] = '\0'; pat = ms.pat + 1; s = ms.s; } else pat++; break; case ')': if (!(flags & MATCH_PAREN)) goto do_default; if (!(flags & MATCH_RECURSING)) { fprintf (stderr, "%s: spurious ')' in pattern\n", progname); return 0; } else if (match (NULL, pat + 1, s, flags, NULL)) { if (msp) { msp->pat = pat; msp->s = s; } return 1; } else return 0; break; case '*': { const char *e; size_t mn = 0; if (mv && !(flags & MATCH_PAREN)) { mn = mv->v_size; VECTOR_PUSH (mv, NULL); } if (flags & MATCH_RIGHT) { e = s; for (pat++; !match (mv, pat, e, flags, msp); e++) if (!*e || (!(flags & MATCH_SLASH) && *e == '/')) { if (mv && !(flags & MATCH_PAREN)) VECTOR_POP (mv); if (msp) msp->s = NULL; return 0; } } else { if ((flags & MATCH_SLASH) || !(e = strchr (s, '/'))) e = s + strlen (s); for (pat++; !match (mv, pat, e, flags, msp); e--) if (e == s) { if (mv && !(flags & MATCH_PAREN)) VECTOR_POP (mv); if (msp) msp->s = NULL; return 0; } } if (mv && !(flags & MATCH_PAREN)) { mv->v_vec[mn] = xmalloc (e - s + 1); memcpy (mv->v_vec[mn], s, e - s); mv->v_vec[mn][e - s] = '\0'; } return 1; break; } case '?': if (!(flags & MATCH_SLASH) && *s == '/') return 0; if (!*s++) return 0; pat++; break; case '[': if (!*s) return 0; if (!(flags & MATCH_SLASH) && *s == '/' && pat[1] == '!') return 0; if (!match_class (&pat, *s++, flags)) return 0; break; case '\\': if (pat[1]) pat++; /* cascade */ default: do_default: if ((flags & MATCH_NOCASE)) { if (tolower (*pat++) != tolower (*s++)) return 0; } else if (*pat++ != *s++) return 0; break; } } } static void run_cmd (char **av) { pid_t pid; int status = -1; pid = fork (); if (pid == -1) { perror ("fork"); exit (71); } if (!pid) { execv (av[0], av); perror (av[0]); _exit (72); } if (waitpid (pid, &status, 0) != pid) { perror ("waitpid"); exit (71); } if (!status) return; if (WIFEXITED (status)) exit (WEXITSTATUS (status)); fprintf (stderr, "%s: died with signal %d\n", av[0], WTERMSIG (status)); exit (75); } static void file2vec (strvec_t *vp, const char *path) { FILE *fp; struct lnbuf buf; int err; fp = fopen (path, "r"); if (!fp) { perror (path); switch (errno) { case EIO: case ESTALE: case EAGAIN: exit (71); break; default: exit (opt_fail); break; } } bzero (&buf, sizeof (buf)); while ((err = readln (&buf, fp, (size_t) -1)) == LNBUF_OK) { assert (buf.size > 0); buf.buf[buf.size - 1] = '\0'; VECTOR_PUSH (vp, xstrdup (buf.buf)); } switch (err) { case LNBUF_EOF: break; case LNBUF_EOFNL: VECTOR_PUSH (vp, xstrdup (buf.buf)); break; default: exit (75); break; } } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s [-gilrs] [-n n] [-c cmd] [-x val]" " {[-p] pattern | -f file} str1 ...\n", progname); exit (64); } int main (int argc, char **argv) { struct option o[] = { { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; int c; strvec_t v, pv; int opt_flags = 0; int opt_num = 0; int opt_num_set = 0; char *opt_cmd = NULL; char *opt_file = NULL; int ok = 0; progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; VECTOR_INIT (&pv); while ((c = getopt_long (argc, argv, "+ilrsc:f:gn:p:qx:", o, NULL)) != -1) switch (c) { case 'v': version (progname, 1); exit (0); break; case 'i': opt_flags |= MATCH_NOCASE; break; case 'l': opt_flags &= ~MATCH_RIGHT; break; case 'r': opt_flags |= MATCH_RIGHT; break; case 'c': opt_cmd = optarg; break; case 'f': if (opt_file) usage (); opt_file = optarg; break; case 'g': opt_flags |= MATCH_PAREN; if (!opt_num_set) opt_num = 1; break; case 'n': opt_num = atoi (optarg); opt_num_set = 1; break; case 'p': VECTOR_PUSH (&pv, xstrdup (optarg)); break; case 'q': opt_num = -1; opt_num_set = 1; break; case 's': opt_flags |= MATCH_SLASH; break; case 'x': opt_fail = atoi (optarg); break; default: usage (); break; } if (!pv.v_size && !opt_file) { if (optind >= argc) usage (); VECTOR_PUSH (&pv, xstrdup (argv[optind++])); } if (opt_file) file2vec (&pv, opt_file); VECTOR_INIT (&v); for (; optind < argc; optind++) { int i; if (opt_cmd) { VECTOR_PUSH (&v, NULL); VECTOR_PUSH (&v, NULL); VECTOR_PUSH (&v, NULL); VECTOR_PUSH (&v, NULL); } for (i = 0; i < pv.v_size; i++) if (match (&v, pv.v_vec[i], argv[optind], opt_flags, NULL)) { ok = 1; if (opt_cmd) { v.v_vec[0] = xstrdup ("/bin/sh"); v.v_vec[1] = xstrdup ("-c"); v.v_vec[2] = xstrdup (opt_cmd); v.v_vec[3] = xstrdup (argv[optind]); VECTOR_PUSH (&v, NULL); run_cmd (v.v_vec); } else if (!opt_num) printf ("%s\n", argv[optind]); else if (opt_num > 0 && opt_num <= v.v_size) printf ("%s\n", v.v_vec[opt_num - 1]); break; } strvec_free (&v); } if (ok) exit (0); exit (opt_fail); } avenger-0.8.5/util/dbexp.c0000644000175000017500000001646311221235216012324 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include "dbexp.h" #define RECOVLK "recov.lock" static int _dbenv_init_lockfd (dbenv *dbe, const char *path) { struct stat sb; char *pb; mode_t m; if (!stat (path, &sb)) { if (!S_ISDIR (sb.st_mode)) { fprintf (stderr, "%s: not a directory\n", path); return ENOTDIR; } } else if (errno != ENOENT) { perror (path); return errno; } else if (mkdir (path, 0700)) { perror (path); return errno; } pb = xmalloc (strlen (path) + sizeof (RECOVLK) + 1); sprintf (pb, "%s/%s", path, RECOVLK); m = umask (0); umask (m); if (m & 02) m |= 04; if (m & 020) m |= 040; dbe->lockfd = open (pb, O_CREAT|O_RDWR, 0666 & ~m); if (dbe->lockfd < 0) { perror (pb); free (pb); return errno; } free (pb); return 0; } dbenv * dbenv_alloc (const char *path) { int err; int recover = DB_RECOVER; dbenv *dbe = xmalloc (sizeof (*dbe)); bzero (dbe, sizeof (*dbe)); err = db_env_create (&dbe->e, 0); if (err) { fprintf (stderr, "db_env_create: %s\n", db_strerror (err)); return NULL; } if (!path) { err = dbe->e->open (dbe->e, NULL, DB_PRIVATE|DB_CREATE|DB_INIT_MPOOL, 0666); if (!err) return dbe; fprintf (stderr, "dbenv_open: %s\n", db_strerror (err)); dbe->e->close (dbe->e, 0); free (dbe); return NULL; } if (_dbenv_init_lockfd (dbe, path)) { dbe->e->close (dbe->e, 0); free (dbe); return NULL; } if (flock (dbe->lockfd, LOCK_EX|LOCK_NB)) { recover = 0; if (flock (dbe->lockfd, LOCK_SH)) { fprintf (stderr, "%s/%s: %s\n", path, RECOVLK, strerror (errno)); close (dbe->lockfd); dbe->e->close (dbe->e, 0); free (dbe); return NULL; } } #if 0 /* For debugging: */ err = dbe->e->set_lg_bsize (dbe->e, 25 * 1024); if (err) fprintf (stderr, "set_lg_bsize: %s\n", db_strerror (err)); dbe->e->set_lg_max (dbe->e, 100 * 1024); if (err) fprintf (stderr, "set_lg_size: %s\n", db_strerror (err)); #endif err = dbe->e->open (dbe->e, path, (DB_INIT_MPOOL|DB_INIT_LOG|DB_INIT_LOCK|DB_INIT_TXN |recover|DB_CREATE), 0666); if (err) { fprintf (stderr, "%s: %s\n", path, db_strerror (err)); close (dbe->lockfd); dbe->e->close (dbe->e, 0); free (dbe); return NULL; } if (recover) flock (dbe->lockfd, LOCK_SH); dbe->txnflag = DB_AUTO_COMMIT; dbe->home = xmalloc (strlen (path) + 1); strcpy (dbe->home, path); return dbe; } void dbenv_free (dbenv *dbe) { dbe->e->close (dbe->e, 0); close (dbe->lockfd); free (dbe); } int dbenv_txn (DB_TXN **tid, dbenv *dbe) { if (dbe->txnflag) return dbe->e->txn_begin (dbe->e, NULL, tid, 0); *tid = NULL; return 0; } int dbenv_commit (DB_TXN *tid) { if (tid) return tid->commit (tid, 0); return 0; } int dbexp_clean (dbexp *dbx) { u_int32_t now = time (NULL); DB_TXN *tid; int i; int err = 0; DBC *c; DBT k, v; while (!err) { if ((err = dbenv_txn (&tid, dbx->dbe))) { fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); return err; } if ((err = dbx->exp->cursor (dbx->exp, tid, &c, 0))) { fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); dbenv_commit (tid); return err; } bzero (&k, sizeof (k)); bzero (&v, sizeof (v)); err = c->c_get (c, &k, &v, DB_FIRST); for (i = 0; !err && i < 20; i++) { if (k.size >= 4) { if (getint (k.data) > now) err = DB_NOTFOUND; else err = c->c_del (c, 0); } if (!err) err = c->c_get (c, &k, &v, DB_NEXT); } if (err && err != DB_NOTFOUND) fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); c->c_close (c); if (!err) err = dbenv_commit (tid); else dbenv_commit (tid); } if (dbx->dbe->home) { #ifdef DB_ARCH_REMOVE dbx->dbe->e->log_archive (dbx->dbe->e, NULL, DB_ARCH_REMOVE); #else /* !DB_ARCH_REMOVE */ int i; char **paths = NULL; int err = dbx->dbe->e->log_archive (dbx->dbe->e, &paths, DB_ARCH_ABS); if (err) fprintf (stderr, "%s: log_archive: %s\n", dbx->path, db_strerror (err)); else if (paths) { for (i = 0; paths[i]; i++) unlink (paths[i]); free (paths); } #endif /* !DB_ARCH_REMOVE */ } if (err == DB_NOTFOUND) return 0; return err; } int dbexp_free (dbexp *dbx, int sync) { int ret = 0; int err; if (dbx->exp) { err = dbx->exp->close (dbx->exp, 0); if (err) { fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); ret = err; } } if (dbx->db) { if (sync && !ret && !dbx->dbe->txnflag) { err = dbx->db->sync (dbx->db, 0); if (!ret && err) { fprintf (stderr, "%s; %s\n", dbx->path, db_strerror (err)); ret = err; } } err = dbx->db->close (dbx->db, 0); if (!ret && err) { fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); ret = err; } } free (dbx->path); free (dbx); return ret; } static int _dbexp_getexp (DB *exp, const DBT *pkey, const DBT *pdata, DBT *skey) { if (pdata->size < 4) return EINVAL; skey->data = pdata->data; skey->size = 4; return 0; } dbexp * dbexp_alloc (dbenv *dbe, const char *path, int rdonly) { int err; int fd; dbexp *dbx = malloc (sizeof (*dbx)); bzero (dbx, sizeof (*dbx)); dbx->dbe = dbe; dbx->path = xmalloc (strlen (path) + 1); strcpy (dbx->path, path); err = db_create (&dbx->db, dbx->dbe->e, 0); if (!err) err = dbx->db->set_flags(dbx->db, DB_CHKSUM); if (!rdonly) { if (!err) err = db_create (&dbx->exp, dbx->dbe->e, 0); if (!err) err = dbx->exp->set_flags(dbx->exp, DB_DUPSORT); } if (err) { fprintf (stderr, "db_create: %s\n", db_strerror (err)); dbexp_free (dbx, 0); return NULL; } err = dbx->db->open (dbx->db, NULL, dbx->path, "db", DB_BTREE, rdonly ? DB_RDONLY : dbx->dbe->txnflag|DB_CREATE, 0666); if (!err) err = dbx->db->fd (dbx->db, &fd); if (err) { fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); dbexp_free (dbx, 0); return NULL; } if (flock (fd, rdonly ? LOCK_SH : LOCK_EX) < 0) { fprintf (stderr, "flock (%s): %s\n", dbx->path, strerror (errno)); dbexp_free (dbx, 0); return NULL; } if (!rdonly) { err = dbx->exp->open (dbx->exp, NULL, dbx->path, "exp", DB_BTREE, dbx->dbe->txnflag|DB_CREATE, 0666); if (!err) err = dbx->db->associate (dbx->db, NULL, dbx->exp, _dbexp_getexp, dbx->dbe->txnflag); if (err) { fprintf (stderr, "%s: %s\n", dbx->path, db_strerror (err)); dbexp_free (dbx, 0); return NULL; } } return dbx; } avenger-0.8.5/util/dbexp.h0000644000175000017500000000250011221235216012314 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "db.h" #ifndef DB_CHKSUM # define DB_CHKSUM DB_CHKSUM_SHA1 #endif /* DB_CHKSUM */ struct dbenv { char *home; int lockfd; DB_ENV *e; int txnflag; }; typedef struct dbenv dbenv; struct dbexp { dbenv *dbe; char *path; DB *db; DB *exp; }; typedef struct dbexp dbexp; dbenv *dbenv_alloc (const char *path); void dbenv_free (dbenv *dbe); int dbenv_txn (DB_TXN **tid, dbenv *dbe); int dbenv_commit (DB_TXN *tid); int dbexp_clean (dbexp *dbx); int dbexp_free (dbexp *dbx, int sync); dbexp *dbexp_alloc (dbenv *dbe, const char *path, int rdonly); avenger-0.8.5/util/sha1.c0000644000175000017500000001420411221235216012045 00000000000000/* $Id$ */ /* * * Copyright (C) 1998 David Mazieres (dm@uun.org) * * 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 * */ /* This file comes from a public domain SHA-1 implementation by Steve * Reid, with numerous performance enhancements added by Emmett * Witchel. */ /* Test Vectors (from FIPS PUB 180-1) "abc" A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 A million repetitions of "a" 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ #include "avutil.h" #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* number of bytes in sha1 block */ #define SHA_BLKSIZE 64 /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ #define blk0(i) (tmp[i] = getint (&block[4*i])) #define blk(i) (tmp[i&15] = rol(tmp[(i+13)&15]^tmp[(i+8)&15] \ ^tmp[(i+2)&15]^tmp[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5); \ w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5); \ w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5); \ w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5); \ w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); enum { blocksize = 64 }; /* Initialize new context */ void sha1_newstate (u_int32_t state[5]) { /* SHA1 initialization constants */ state[0] = 0x67452301; state[1] = 0xefcdab89; state[2] = 0x98badcfe; state[3] = 0x10325476; state[4] = 0xc3d2e1f0; } /* Hash a single 512-bit block. This is the core of the algorithm. */ void sha1_transform (u_int32_t state[5], const u_char block[64]) { register u_int32_t a, b, c, d, e; u_int32_t tmp[16]; /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ /* Copy from block to tmp folded into computation */ R0 (a, b, c, d, e, 0); R0 (e, a, b, c, d, 1); R0 (d, e, a, b, c, 2); R0 (c, d, e, a, b, 3); R0 (b, c, d, e, a, 4); R0 (a, b, c, d, e, 5); R0 (e, a, b, c, d, 6); R0 (d, e, a, b, c, 7); R0 (c, d, e, a, b, 8); R0 (b, c, d, e, a, 9); R0 (a, b, c, d, e, 10); R0 (e, a, b, c, d, 11); R0 (d, e, a, b, c, 12); R0 (c, d, e, a, b, 13); R0 (b, c, d, e, a, 14); R0 (a, b, c, d, e, 15); R1 (e, a, b, c, d, 16); R1 (d, e, a, b, c, 17); R1 (c, d, e, a, b, 18); R1 (b, c, d, e, a, 19); R2 (a, b, c, d, e, 20); R2 (e, a, b, c, d, 21); R2 (d, e, a, b, c, 22); R2 (c, d, e, a, b, 23); R2 (b, c, d, e, a, 24); R2 (a, b, c, d, e, 25); R2 (e, a, b, c, d, 26); R2 (d, e, a, b, c, 27); R2 (c, d, e, a, b, 28); R2 (b, c, d, e, a, 29); R2 (a, b, c, d, e, 30); R2 (e, a, b, c, d, 31); R2 (d, e, a, b, c, 32); R2 (c, d, e, a, b, 33); R2 (b, c, d, e, a, 34); R2 (a, b, c, d, e, 35); R2 (e, a, b, c, d, 36); R2 (d, e, a, b, c, 37); R2 (c, d, e, a, b, 38); R2 (b, c, d, e, a, 39); R3 (a, b, c, d, e, 40); R3 (e, a, b, c, d, 41); R3 (d, e, a, b, c, 42); R3 (c, d, e, a, b, 43); R3 (b, c, d, e, a, 44); R3 (a, b, c, d, e, 45); R3 (e, a, b, c, d, 46); R3 (d, e, a, b, c, 47); R3 (c, d, e, a, b, 48); R3 (b, c, d, e, a, 49); R3 (a, b, c, d, e, 50); R3 (e, a, b, c, d, 51); R3 (d, e, a, b, c, 52); R3 (c, d, e, a, b, 53); R3 (b, c, d, e, a, 54); R3 (a, b, c, d, e, 55); R3 (e, a, b, c, d, 56); R3 (d, e, a, b, c, 57); R3 (c, d, e, a, b, 58); R3 (b, c, d, e, a, 59); R4 (a, b, c, d, e, 60); R4 (e, a, b, c, d, 61); R4 (d, e, a, b, c, 62); R4 (c, d, e, a, b, 63); R4 (b, c, d, e, a, 64); R4 (a, b, c, d, e, 65); R4 (e, a, b, c, d, 66); R4 (d, e, a, b, c, 67); R4 (c, d, e, a, b, 68); R4 (b, c, d, e, a, 69); R4 (a, b, c, d, e, 70); R4 (e, a, b, c, d, 71); R4 (d, e, a, b, c, 72); R4 (c, d, e, a, b, 73); R4 (b, c, d, e, a, 74); R4 (a, b, c, d, e, 75); R4 (e, a, b, c, d, 76); R4 (d, e, a, b, c, 77); R4 (c, d, e, a, b, 78); R4 (b, c, d, e, a, 79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } void sha1_state2bytes (void *_cp, const u_int32_t state[5]) { u_char *cp = (u_char *) (_cp); size_t i; for (i = 0; i < 5; i++) { u_int32_t v = *state++; cp[0] = v >> 24; cp[1] = v >> 16; cp[2] = v >> 8; cp[3] = v; cp += 4; } } static void sha1_consume (mdblock *_mdb, const u_char block[64]) { sha1_ctx *sc = (sha1_ctx *) _mdb; sha1_transform (sc->state, block); } void sha1_init (sha1_ctx *sc) { mdblock_init (&sc->mdb, sha1_consume); sha1_newstate (sc->state); } void sha1_update (sha1_ctx *sc, const void *bytes, size_t len) { mdblock_update (&sc->mdb, bytes, len); } void sha1_final (sha1_ctx *sc, u_char out[20]) { mdblock_finish (&sc->mdb, 1); sha1_state2bytes (out, sc->state); bzero (sc->state, sizeof (sc->state)); } void hmac_sha1 (void *out, const char *key, const void *data, u_int dlen) { char block[64]; sha1_ctx sc; unsigned i; sha1_init (&sc); memset (block, 0x36, sizeof (block)); for (i = 0; i < sizeof (block) && key[i]; i++) block[i] ^= key[i]; sha1_update (&sc, block, sizeof (block)); sha1_update (&sc, data, dlen); sha1_final (&sc, out); sha1_init (&sc); for (i = 0; i < sizeof (block); i++) block[i] ^= 0x36 ^ 0x5c; sha1_update (&sc, block, sizeof (block)); sha1_update (&sc, out, 20); sha1_final (&sc, out); } avenger-0.8.5/util/aliascheck.c0000644000175000017500000001245311221235216013304 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include "db.h" #include #include #include "getopt_long.h" int check_alias_dbm (const char *file, const char *user, int map); char *progname; static inline int checkfile (const char *file) { struct stat sb; if (stat (file, &sb) || !S_ISREG (sb.st_mode)) return -1; return 0; } static char * dotqmail (const char *user, int nchop) { static const char dqm[] = ".qmail-"; static const char def[] = "default"; char *p; char *res; res = xmalloc (sizeof (dqm) + sizeof (def) + strlen (user)); strcpy (res, dqm); strcat (res, user); for (p = res + strlen (res); nchop > 0; nchop--) { *p = '\0'; p = strrchr (res, '-'); if (!p || !*p) return NULL; } if (*p) strcpy (p + 1, def); return res; } int check_alias_qmail (const char *alias, const char *user) { struct passwd *pw; char *p; int i; if (!(pw = getpwnam (alias))) { fprintf (stderr, "%s: no such user\n", alias); return 2; } if (chdir (pw->pw_dir)) { fprintf (stderr, "cannot chdir %s: %s\n", pw->pw_dir, strerror (errno)); return 2; } for (i = 0; (p = dotqmail (user, i)); i++) { /* printf ("trying %s\n", p); */ if (!checkfile (p)) { printf ("%s/%s\n", pw->pw_dir, p); free (p); return 0; } free (p); } return 1; } void db_fatal (int err, const char *) __attribute__ ((noreturn)); void db_fatal (int err, const char *msg) { if (msg) fprintf (stderr, "%s: %s\n", msg, db_strerror (err)); else fprintf (stderr, "%s\n", db_strerror (err)); exit (2); } int check_alias (const char *file, const char *user, int map) { int err; DB *db; DBT k, v; err = db_create (&db, NULL, 0); if (err) { fprintf (stderr, "db_create: %s\n", db_strerror (err)); return check_alias_dbm (file, user, map); } err = db->open (db, NULL, file, NULL, DB_UNKNOWN, DB_RDONLY, 0666); if (err) { db->close (db, 0); return check_alias_dbm (file, user, map); } bzero (&k, sizeof (k)); bzero (&v, sizeof (v)); if (!map) { k.data = "@"; k.size = 2; err = db->get (db, NULL, &k, &v, 0); if (err) { if (err != DB_NOTFOUND) fprintf (stderr, "%s: %s\n", file, db_strerror (err)); else fprintf (stderr, "%s: incomplete/corrupted alias database\n", file); db->close (db, 0); return 2; } } k.data = (char *) user; k.size = strlen (user); if (!map) k.size++; err = db->get (db, NULL, &k, &v, 0); if (err == DB_NOTFOUND) { db->close (db, 0); return 1; } else if (err) { db->close (db, 0); fprintf (stderr, "%s: %s\n", file, db_strerror (err)); return 2; } printf ("%.*s\n", (int) v.size, (char *) v.data); db->close (db, 0); return 0; } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s [--nopwd] name alias-file\n" " %s --map [--case] key map-file\n" " %s --qmail [--nopwd] name alias-user\n", progname, progname, progname); exit (1); } int main (int argc, char **argv) { int mode = 0; int opt_nopwd = 0; int opt_map = 0; int opt_case = 0; struct option o[] = { { "version", no_argument, &mode, 'v' }, { "qmail", no_argument, &mode, 'q' }, { "nopwd", no_argument, &opt_nopwd, 1 }, { "map", no_argument, &opt_map, 1 }, { "case", no_argument, &opt_case, 1 }, { NULL, 0, NULL, 0 } }; int c; char *p, *q, *user, *alias = NULL; int ret; progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; while ((c = getopt_long (argc, argv, "+", o, NULL)) != -1) switch (c) { case 0: break; default: usage (); } if (optind + 2 == argc) alias = argv[optind+1]; else if (optind + 1 != argc) usage (); if (opt_map) { opt_nopwd = 1; if (mode == 'q' || !alias) usage (); } if (mode == 'v') version (progname, 1); p = argv[optind]; q = user = xmalloc (strlen (p) + 1); if (opt_case) strcpy (q, p); else while ((*q++ = tolower (*p++))) ; if (mode == 'q') { if (!alias) alias = "alias"; ret = check_alias_qmail (alias, user); } else { if (!alias && !checkfile ("/etc/mail/aliases.db")) alias = "/etc/mail/aliases.db"; if (!alias && !checkfile ("/etc/aliases.db")) alias = "/etc/aliases.db"; ret = check_alias (alias, user, opt_map); if (ret == 2) fprintf (stderr, "%s: bad alias file\n", alias); } if (ret && !opt_nopwd && getpwnam (user)) { printf ("%s\n", user); exit (0); } exit (ret); } avenger-0.8.5/util/smtpdcheck.c0000644000175000017500000001152611221235216013342 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include #include #include #include #include #include #include #include "getopt_long.h" char *progname; char *stop_name; struct in_addr stop_ip; int stop_ip_set; #ifndef HAVE_STRCASECMP int strcasecmp (const char *s1, const char *s2) { while (tolower (*s1) == tolower (*s2++)) if (!*s1++) return 0; return tolower (*s1) - tolower (s2[-1]); } #endif /* HAVE_STRCASECMP */ static int check_stop (struct hostent *h) { int i; if (stop_name && !strcasecmp (stop_name, h->h_name)) return 1; for (i = 0; h->h_addr_list[i]; i++) if (stop_ip.s_addr == ((struct in_addr *) h->h_addr_list[i])->s_addr) return 1; return 0; } static sigjmp_buf tmojump; static void dojump (int sig) { siglongjmp (tmojump, sig); } /* Return: 1 if server ok, 0 if server not ok, -1 if stop */ static int check_server (const char *name, int timeout) { struct hostent *h; struct sockaddr_in sin; int s; struct sigaction sa, osa; int n; char buf[4]; s = socket (AF_INET, SOCK_STREAM, 0); bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; if (s < 0 || bind (s, (struct sockaddr *) &sin, sizeof (sin)) < 0) { perror ("TCP socket"); exit (2); } sin.sin_port = htons (25); bzero (&sa, sizeof (sa)); sa.sa_handler = dojump; sa.sa_flags = SA_RESETHAND; if (sigaction (SIGALRM, &sa, &osa) < 0) { perror ("sigaction"); exit (2); } if (sigsetjmp (tmojump, 1)) { sigaction (SIGALRM, &osa, NULL); close (s); return 0; } alarm (timeout); h = gethostbyname (name); if (!h) { alarm (0); sigaction (SIGALRM, &osa, NULL); close (s); return 0; } sin.sin_addr = *(struct in_addr *) h->h_addr; if (check_stop (h)) { alarm (0); sigaction (SIGALRM, &osa, NULL); close (s); return -1; } if (connect (s, (struct sockaddr *) &sin, sizeof (sin)) < 0) { alarm (0); sigaction (SIGALRM, &osa, NULL); close (s); return 0; } n = read (s, buf, sizeof (buf)); alarm (0); sigaction (SIGALRM, &osa, NULL); close (s); if (n < 4 || buf[0] != '2' || !isdigit (buf[1]) || !isdigit (buf[2]) || (buf[3] != ' ' && buf[3] != '-' && buf[3] != '\r')) return 0; return 1; } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s [--stop {ip-addr|name}] [prio:]server1" " [[prio:]server2 ...]\n", progname); exit (1); } int main (int argc, char **argv) { struct option o[] = { { "version", no_argument, NULL, 'v' }, { "stop", required_argument, NULL, 's' }, { "timeout", required_argument, NULL, 't' }, { NULL, 0, NULL, 0 } }; int c, n; int timeout = 10; int ok_pri = -1; char *ok_name = NULL; progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; while ((c = getopt_long (argc, argv, "+s:t:", o, NULL)) != -1) switch (c) { case 'v': version (progname, 1); break; case 's': if (stop_ip_set || stop_name) usage (); else if (inet_aton (optarg, &stop_ip) == 1) stop_ip_set = 1; else { struct hostent *h = gethostbyname (optarg); if (!h) { fprintf (stderr, "%s: no such host\n", optarg); exit (2); } stop_name = xmalloc (1 + strlen (h->h_name)); strcpy (stop_name, h->h_name); stop_ip_set = 1; stop_ip = *(struct in_addr *) h->h_addr; } break; case 't': if (sscanf (optarg, "%u%n", &timeout, &n) != 1 || timeout < 0 || (size_t) n != strlen (optarg)) usage (); break; default: usage (); } for (; optind < argc; optind++) { int pri; char *p; n = 0; sscanf (argv[optind], "%d:%n", &pri, &n); if (!n) { pri = -1; p = argv[optind]; } else p = argv[optind] + n; if (ok_name && pri > ok_pri) break; switch (check_server (p, timeout)) { case -1: exit (0); break; case 1: ok_name = p; ok_pri = pri; break; } } if (ok_name) { printf ("%s\n", ok_name); exit (1); } exit (0); } avenger-0.8.5/util/.gitignore0000644000175000017500000000011311221235216013027 00000000000000aliascheck dbutil edinplace escape macutil match omacutil smtpdcheck synos avenger-0.8.5/util/Makefile.am0000644000175000017500000000323311357424376013122 00000000000000## Process this file with automake to produce Makefile.in # $Id$ $(PROGRAMS): libavutil.a AM_CPPFLAGS = -DAVUTIL_MAIN=1 bin_PROGRAMS = aliascheck dbutil edinplace escape synos macutil \ match smtpdcheck noinst_PROGRAMS = omacutil noinst_LIBRARIES = libavutil.a noinst_HEADERS = avutil.h dbexp.h synos.h vector.h dbutil_SOURCES = dbutil.c dbutil_LDADD = -L. -lavutil $(DB_LIB) dbutil_LDFLAGS = $(LDFLAGS) -static macutil_SOURCES = macutil.c macutil_LDADD = -L. -lavutil omacutil_SOURCES = omacutil.c omacutil_LDADD = -L. -lavutil edinplace_SOURCES = edinplace.c edinplace_LDADD = -L. -lavutil escape_SOURCES = escape.c escape_LDADD = -L. -lavutil aliascheck_SOURCES = aliascheck.c aliascheck_dbm.c aliascheck_LDADD = -L. -lavutil $(DB_LIB) $(NDBM_LIBS) # We make this -static (meaning libtool archives static) # because we don't want to start failing when someone updates # the sleepycat database on the system aliascheck_LDFLAGS = $(LDFLAGS) -static smtpdcheck_SOURCES = smtpdcheck.c smtpdcheck_LDADD = -L. -lavutil match_SOURCES = match.c match_LDADD = -L. -lavutil synos_SOURCES = synos.c synos_LDADD = -L. -lavutil libavutil_a_SOURCES = armor.c aes.c buf.c clock_gettime.c dbexp.c \ flock.c getopt_long.c mdblock.c sha1.c straux.c time.c version.c aliascheck_dbm.o: $(srcdir)/aliascheck_dbm.c $(srcdir)/avutil.h $(COMPILE) $(NDBM_INC) -c $(srcdir)/aliascheck_dbm.c install-exec-hook: rm -f $(DESTDIR)$(bindir)/sendmac$(EXEEXT) ln $(DESTDIR)$(bindir)/macutil$(EXEEXT) \ $(DESTDIR)$(bindir)/sendmac$(EXEEXT) uninstall-hook: rm -f $(DESTDIR)$(bindir)/sendmac$(EXEEXT) CLEANFILES = core *.core *~ EXTRA_DIST = .gitignore omacutil.c MAINTAINERCLEANFILES = Makefile.in avenger-0.8.5/util/macutil.c0000644000175000017500000002573311221235216012660 00000000000000/* $Id$ */ /* * * Copyright (C) 2004 David Mazieres (dm@uun.org) * * 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 * */ #include "avutil.h" #include "getopt_long.h" char *progname; long opt_date; char *opt_pwfile; char *opt_expire; char *opt_aux; char *opt_sender; char *opt_from; char *opt_fromexp; int opt_quiet; int opt_verbose = 0; struct addrinfo { u_int32_t time; /* Expiration time */ unsigned nonce; /* 24-bit nonce */ u_char reserved : 2; /* Must be zero */ u_char duration : 6; /* ceil (log_2 (seconds valid)) */ char mbz[8]; /* must be zero */ }; struct binaddr { char time[4]; /* message timestamp */ char nonce[3]; /* nonce */ char rd; /* reserved/duration */ char mbz[8]; /* zero or hash of aux string */ }; static inline void put3b (void *_dp, u_int32_t val) { unsigned char *dp = (unsigned char *) (_dp); dp[0] = val >> 16; dp[1] = val >> 8; dp[2] = val; } static inline u_int32_t get3b (const void *_dp) { const unsigned char *dp = (const unsigned char *) (_dp); return dp[0] << 16 | dp[1] << 8 | dp[2]; } static void h2nai (struct binaddr *out, const struct addrinfo *in) { putint (out->time, in->time); put3b (out->nonce, in->nonce); out->rd = in->duration & 0x3f; bzero (out->mbz, sizeof (out->mbz)); } static void n2hai (struct addrinfo *out, const struct binaddr *in) { out->time = getint (in->time); out->nonce = get3b (in->nonce); out->duration = in->rd & 0x3f; out->reserved = (unsigned) in->rd >> 6; memcpy (out->mbz, in->mbz, sizeof (out->mbz)); } char * getmacpw (FILE *pwfile, const char *aux) { static char pwbuf[300]; char *p; static char hashbuf[sha1_hashsize]; again: if (!fgets (pwbuf, sizeof (pwbuf), pwfile)) return NULL; p = strchr (pwbuf, '\n'); if (!p) { fprintf (stderr, "fatal: line too long in %s\n", opt_pwfile); exit (1); } if (p - pwbuf > 64) { fprintf (stderr, "%s: skipping line longer than 64 characters\n", opt_pwfile); goto again; } *p = '\0'; if (aux) hmac_sha1 (hashbuf, pwbuf, aux, strlen (aux) + 1); else hmac_sha1 (hashbuf, pwbuf, NULL, 0); bzero (pwbuf, sizeof (pwbuf)); return hashbuf; } char * mkaddr (const char *pw, time_t exp) { struct addrinfo ai; struct binaddr bi; struct timespec ts; aes_ctx aes; char *asc; ai.time = exp; clock_gettime (CLOCK_REALTIME, &ts); ai.nonce = ts.tv_nsec >> 6; ai.reserved = 0; if (exp > opt_date) { u_long dur = exp - opt_date + 1; int logdur = 0; while (dur > 0) { logdur++; dur = dur >> 1; } ai.duration = logdur; } else ai.duration = 0; h2nai (&bi, &ai); aes_setkey (&aes, pw, 16); aes_encrypt (&aes, &bi, &bi); asc = armor32 (&bi, 16); return asc; } void do_gen (const char *pw, time_t exp) { char *asc = mkaddr (pw, exp); printf ("%s\n", asc); free (asc); } void do_check (FILE *pwfile, char *asc, const char *auxsrc) { char dbuf[16]; char *pw; aes_ctx aes; unsigned long now = opt_date; int bad; struct binaddr bi; struct addrinfo ai; unsigned i; if (dearmor32len (asc) != sizeof (dbuf) || (size_t) dearmor32 (dbuf, asc) != strlen (asc)) { if (!opt_quiet) fprintf (stderr, "bad input format\n"); exit (1); } /* dearmor32 might ignore trailing bits, so double check we would * have produced this output. (This only matters for security if * you are imposing some sort of quota per token, in which case * users could generate more valid looking tokens by manipulating * the last character of the token.) */ pw = armor32 (dbuf, 16); bad = strcmp (pw, asc); free (pw); if (bad) { if (!opt_quiet) fprintf (stderr, "bad input format\n"); exit (1); } do { bad = 0; pw = getmacpw (pwfile, auxsrc); if (!pw) { if (!opt_quiet) fprintf (stderr, "verification failed\n"); exit (1); } aes_setkey (&aes, pw, 16); aes_decrypt (&aes, &bi, dbuf); n2hai (&ai, &bi); for (i = 0; i < sizeof (ai.mbz); i++) if (ai.mbz[i]) bad++; if (opt_verbose) { time_t t = ai.time; printf ("Decrypted to:\n"); printf (" Time: %lu = %s", (unsigned long) t, ctime (&t)); printf (" Nonce: 0x%x\n", ai.nonce); printf ("reserved: %d\n", (int) ai.reserved); printf ("duration: %d\n", (int) ai.duration); printf (" mbz: %s\n", bad ? "bad" : "ok"); } if (ai.reserved) bad++; if ((ai.time - now) >> ai.duration) bad++; if (now > ai.time) bad++; } while (bad); bzero (&aes, sizeof (aes)); } char * firstpw (void) { char *ret; FILE *pwfile = fopen (opt_pwfile, "r"); if (!pwfile) { perror (opt_pwfile); return NULL; } ret = getmacpw (pwfile, opt_aux); fclose (pwfile); return ret; } char * mksender (long exp, const char *aux) { char *p, *q, *s, *sender; s = opt_sender; if (!s) s = getenv ("MACUTIL_SENDER"); if (!s) { fprintf (stderr, "%s: no MACUTIL_SENDER environment variable\n", progname); return NULL; } p = strchr (s, '@'); if (!p) p = s + strlen (s); for (q = p; *q != '*'; q--) if (q == s) { fprintf (stderr, "%s: MACUTIL_SENDER must contain '*'\n", progname); return NULL; } p = firstpw (); if (!p) return NULL; sender = mkaddr (p, exp); bzero (p, 20); p = sender; sender = xmalloc ((q - s) + strlen (q) + strlen (p)); sprintf (sender, "%.*s%s%s", (int) (q - s), s, p, *q ? q + 1 : ""); free (p); return sender; } int do_sendmail (int argc, char **argv) { char *sendmail = getenv ("MACUTIL_SENDMAIL"); char *sender = NULL; char **av; long exp; exp = parse_expire (opt_expire, opt_date); if (exp != -1) sender = mksender (exp, opt_aux); av = xmalloc ((argc + 3) * sizeof (av[0])); av[0] = sendmail ? sendmail : "sendmail"; av[1] = "-f"; av[2] = sender; memcpy (av + 3, argv + 1, (argc - 1) * sizeof (av[0])); av[argc+2] = NULL; if (sender) execvp (av[0], av); else { av[2] = av[0]; execvp (av[0], av + 2); } perror (av[0]); exit (1); } static char * default_macpass (void) { char defsuf[] = "/.avenger/.macpass"; char *home = getenv ("HOME"); char *ret; if (!home) { fprintf (stderr, "no HOME environment variable set\n"); exit (1); } ret = xmalloc (strlen (home) + sizeof (defsuf)); sprintf (ret, "%s%s", home, defsuf); return ret; } static void usage (void) __attribute__ ((noreturn)); static void usage (void) { fprintf (stderr, "usage: %s --gen [options]\n", progname); fprintf (stderr, " %s --sender [options] address-template\n", progname); fprintf (stderr, " %s --check [options] nonce\n", progname); fprintf (stderr, " %s --sendmail [sendmail options]\n", progname); fprintf (stderr, "options are:\n" " --aux=string Non-secret string to perturb algorithm\n" " --passfile=file File containing password(s)\n" " --expire=date Set expiration date with --gen\n" " --date=date Act as if current time were date\n"); exit (1); } int main (int argc, char **argv) { int mode = 0; int c; struct option o[] = { { "version", no_argument, NULL, 'v' }, { "check", no_argument, &mode, 'c' }, { "gen", no_argument, &mode, 'g' }, { "passfile", required_argument, NULL, 'p' }, { "expire", required_argument, NULL, 'e' }, { "date", required_argument, NULL, 'd' }, { "aux", required_argument, NULL, 'a' }, { "from", required_argument, NULL, 'f' }, { "sender", required_argument, NULL, 's' }, { "fromexp", required_argument, NULL, 'E' }, { "sendmail", no_argument, NULL, 'M' }, { NULL, 0, NULL, 0 } }; FILE *pwfile; opt_date = time (NULL); opt_expire = getenv ("MACUTIL_EXPIRE"); if (!opt_expire) opt_expire = "+21D"; opt_pwfile = getenv ("MACUTIL_PASSFILE"); if (!opt_pwfile) opt_pwfile = default_macpass (); progname = strrchr (argv[0], '/'); if (progname) progname++; else progname = argv[0]; if (!strncmp (progname, "send", 4)) return do_sendmail (argc, argv); while ((c = getopt_long (argc, argv, "+Vcf:gNOqp:s:", o, NULL)) != -1) switch (c) { case 0: break; case 'E': opt_fromexp = optarg; break; case 'M': return do_sendmail (argc - optind + 1, argv + optind - 1); case 'a': opt_aux = optarg; break; case 'v': version (progname, 1); break; case 'V': opt_verbose = 1; break; case 'd': opt_date = parse_expire (optarg, time (NULL)); break; case 'e': opt_expire = optarg; break; case 'p': opt_pwfile = optarg; break; case 'q': opt_quiet = 1; break; case 'f': opt_from = optarg; break; case 's': opt_sender = optarg; break; case 'c': case 'g': mode = c; break; default: usage (); break; } argv += optind; argc -= optind; if (opt_sender) { if (mode == 'c') usage (); mode = 's'; } if (!mode && opt_from && (opt_sender = getenv ("MACUTIL_SENDER"))) mode = 's'; if (!mode || opt_date == -1) usage (); pwfile = fopen (opt_pwfile, "r"); if (!pwfile) { perror (opt_pwfile); exit (1); } switch (mode) { case 'g': { long exp = parse_expire (opt_expire, opt_date); char *pw = getmacpw (pwfile, opt_aux); if (argc || exp == -1) usage (); if (!pw) { fprintf (stderr, "%s: no passwords\n", opt_pwfile); exit (1); } do_gen (pw, exp); bzero (pw, 20); break; } case 'c': if (argc != 1) usage (); do_check (pwfile, argv[0], opt_aux); break; case 's': { char *from; long exp = parse_expire (opt_expire, opt_date); if (argc || exp == -1) usage (); from = mksender (exp, opt_aux); if (!from) exit (1); if (opt_from) { printf ("%s", opt_from); if (opt_fromexp || (opt_fromexp = getenv ("MACUTIL_FROMEXP"))) { time_t t = exp; char buf[80]; strftime (buf, sizeof (buf), "%d %b %Y", localtime (&t)); buf[sizeof (buf) - 1] = '\0'; printf (" (%s%s%s)", opt_fromexp, *opt_fromexp ? " " : "", buf); } printf (" <%s>\n", from); } else printf ("%s\n", from); exit (0); break; } default: usage (); break; } #if 0 hmac_sha1 (buf, argv[1], argv[2], strlen (argv[2])); for (i = 0; i < sizeof (buf); i++) printf ("%02x", buf[i]); printf ("\n"); #endif return 0; } avenger-0.8.5/util/getopt_long.c0000644000175000017500000003626011221235216013540 00000000000000/* $Id$ */ /* * Copyright (c) 2002 Todd C. Miller * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Sponsored in part by the Defense Advanced Research Projects * Agency (DARPA) and Air Force Research Laboratory, Air Force * Materiel Command, USAF, under agreement number F39502-99-1-0512. */ /*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include "getopt_long.h" #define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ #ifdef REPLACE_GETOPT int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = '?'; /* character checked for validity */ int optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #endif #define PRINT_ERROR ((opterr) && (*options != ':')) #define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ #define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ #define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ /* return values */ #define BADCH (int)'?' #define BADARG ((*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 #define EMSG "" static int getopt_internal (int, char *const *, const char *, const struct option *, int *, int); static int parse_long_options (char *const *, const char *, const struct option *, int *, int); static int gcd (int, int); static void permute_args (int, int, int, char *const *); static char *place = EMSG; /* option letter processing */ /* XXX: set optreset to 1 rather than these two */ static int nonopt_start = -1; /* first non option argument (for permute) */ static int nonopt_end = -1; /* first option after non options (for permute) */ /* Error messages */ static const char recargchar[] = "option requires an argument -- %c\n"; static const char recargstring[] = "option requires an argument -- %s\n"; static const char ambig[] = "ambiguous option -- %.*s\n"; static const char noarg[] = "option doesn't take an argument -- %.*s\n"; static const char illoptchar[] = "unknown option -- %c\n"; static const char illoptstring[] = "unknown option -- %s\n"; /* * Compute the greatest common divisor of a and b. */ static int gcd (int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return (b); } /* * Exchange the block from nonopt_start to nonopt_end with the block * from nonopt_end to opt_end (keeping the same order of arguments * in each block). */ static void permute_args (int panonopt_start, int panonopt_end, int opt_end, char *const *nargv) { int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; /* * compute lengths of blocks and number and size of cycles */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd (nnonopts, nopts); cyclelen = (opt_end - panonopt_start) / ncycle; for (i = 0; i < ncycle; i++) { cstart = panonopt_end + i; pos = cstart; for (j = 0; j < cyclelen; j++) { if (pos >= panonopt_end) pos -= nnonopts; else pos += nopts; swap = nargv[pos]; /* LINTED const cast */ ((char **) nargv)[pos] = nargv[cstart]; /* LINTED const cast */ ((char **) nargv)[cstart] = swap; } } } /* * parse_long_options -- * Parse long options in argc/argv argument vector. * Returns -1 if short_too is set and the option does not match long_options. */ static int parse_long_options (char *const *nargv, const char *options, const struct option *long_options, int *idx, int short_too) { char *current_argv, *has_equal; size_t current_argv_len; int i, match; current_argv = place; match = -1; optind++; if ((has_equal = strchr (current_argv, '=')) != NULL) { /* argument found (--option=arg) */ current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen (current_argv); for (i = 0; long_options[i].name; i++) { /* find matching long option */ if (strncmp (current_argv, long_options[i].name, current_argv_len)) continue; if (strlen (long_options[i].name) == current_argv_len) { /* exact match */ match = i; break; } /* * If this is a known short option, don't allow * a partial match of a single character. */ if (short_too && current_argv_len == 1) continue; if (match == -1) /* partial match */ match = i; else { /* ambiguous abbreviation */ if (PRINT_ERROR) fprintf (stderr, ambig, (int) current_argv_len, current_argv); optopt = 0; return (BADCH); } } if (match != -1) { /* option found */ if (long_options[match].has_arg == no_argument && has_equal) { if (PRINT_ERROR) fprintf (stderr, noarg, (int) current_argv_len, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; return (BADARG); } if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use next nargv */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' indicates no error * should be generated. */ if (PRINT_ERROR) fprintf (stderr, recargstring, current_argv); /* * XXX: GNU sets optopt to val regardless of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; --optind; return (BADARG); } } else { /* unknown option */ if (short_too) { --optind; return (-1); } if (PRINT_ERROR) fprintf (stderr, illoptstring, current_argv); optopt = 0; return (BADCH); } if (idx) *idx = match; if (long_options[match].flag) { *long_options[match].flag = long_options[match].val; return (0); } else return (long_options[match].val); } /* * getopt_internal -- * Parse argc/argv argument vector. Called by user level routines. */ static int getopt_internal (int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx, int flags) { char *oli; /* option letter list index */ int optchar, short_too; static int posixly_correct = -1; if (options == NULL) return (-1); /* * Disable GNU extensions if POSIXLY_CORRECT is set or options * string begins with a '+'. */ if (posixly_correct == -1) posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL); if (posixly_correct || *options == '+') flags &= ~FLAG_PERMUTE; else if (*options == '-') flags |= FLAG_ALLARGS; if (*options == '+' || *options == '-') options++; /* * XXX Some GNU programs (like cvs) set optind to 0 instead of * XXX using optreset. Work around this braindamage. */ if (optind == 0) optind = optreset = 1; optarg = NULL; if (optreset) nonopt_start = nonopt_end = -1; start: if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc) { /* end of argument vector */ place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ permute_args (nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* * If we skipped non-options, set optind * to the first of them. */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr (options, '-') == NULL)) { place = EMSG; /* found non-option */ if (flags & FLAG_ALLARGS) { /* * GNU extension: * return non-option as argument to option 1 */ optarg = nargv[optind++]; return (INORDER); } if (!(flags & FLAG_PERMUTE)) { /* * If no permutation wanted, stop parsing * at first non-option. */ return (-1); } /* do permutation */ if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { permute_args (nonopt_start, nonopt_end, optind, nargv); nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; /* process next argument */ goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; /* * If we have "-" do nothing, if "--" we are done. */ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { optind++; place = EMSG; /* * We found an option (--), so if we skipped * non-options, we have to permute. */ if (nonopt_end != -1) { permute_args (nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; return (-1); } } /* * Check long options if: * 1) we were passed some * 2) the arg is not just "-" * 3) either the arg starts with -- we are getopt_long_only() */ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) { short_too = 0; if (*place == '-') place++; /* --foo long option */ else if (*place != ':' && strchr (options, *place) != NULL) short_too = 1; /* could be short option too */ optchar = parse_long_options (nargv, options, long_options, idx, short_too); if (optchar != -1) { place = EMSG; return (optchar); } } if ((optchar = (int) *place++) == (int) ':' || (optchar == (int) '-' && *place != '\0') || (oli = strchr (options, optchar)) == NULL) { /* * If the user specified "-" and '-' isn't listed in * options, return -1 (non-option) as per POSIX. * Otherwise, it is an unknown option character (or ':'). */ if (optchar == (int) '-' && *place == '\0') return (-1); if (!*place) ++optind; if (PRINT_ERROR) fprintf (stderr, illoptchar, optchar); optopt = optchar; return (BADCH); } if (long_options != NULL && optchar == 'W' && oli[1] == ';') { /* -W long-option */ if (*place) /* no space */ /* NOTHING */ ; else if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) fprintf (stderr, recargchar, optchar); optopt = optchar; return (BADARG); } else /* white space */ place = nargv[optind]; optchar = parse_long_options (nargv, options, long_options, idx, 0); place = EMSG; return (optchar); } if (*++oli != ':') { /* doesn't take argument */ if (!*place) ++optind; } else { /* takes (optional) argument */ optarg = NULL; if (*place) /* no white space */ optarg = place; /* XXX: disable test for :: if PC? (GNU doesn't) */ else if (oli[1] != ':') { /* arg not optional */ if (++optind >= nargc) { /* no arg */ place = EMSG; if (PRINT_ERROR) fprintf (stderr, recargchar, optchar); optopt = optchar; return (BADARG); } else optarg = nargv[optind]; } else if (!(flags & FLAG_PERMUTE)) { /* * If permutation is disabled, we can accept an * optional arg separated by whitespace. */ if (optind + 1 < nargc) optarg = nargv[++optind]; } place = EMSG; ++optind; } /* dump back option letter */ return (optchar); } #ifdef REPLACE_GETOPT /* * getopt -- * Parse argc/argv argument vector. * * [eventually this will replace the BSD getopt] */ int getopt (int nargc, char *const *nargv, const char *options) { /* * We dont' pass FLAG_PERMUTE to getopt_internal() since * the BSD getopt(3) (unlike GNU) has never done this. * * Furthermore, since many privileged programs call getopt() * before dropping privileges it makes sense to keep things * as simple (and bug-free) as possible. */ return (getopt_internal (nargc, nargv, options, NULL, NULL, 0)); } #endif /* REPLACE_GETOPT */ /* * getopt_long -- * Parse argc/argv argument vector. */ int getopt_long (int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal (nargc, nargv, options, long_options, idx, FLAG_PERMUTE)); } /* * getopt_long_only -- * Parse argc/argv argument vector. */ int getopt_long_only (int nargc, char *const *nargv, const char *options, const struct option *long_options, int *idx) { return (getopt_internal (nargc, nargv, options, long_options, idx, FLAG_PERMUTE | FLAG_LONGONLY)); } avenger-0.8.5/acinclude.m40000644000175000017500000013641313357046317012306 00000000000000dnl $Id$ dnl dnl Find full path to program dnl AC_DEFUN([SFS_PATH_PROG], [AC_PATH_PROG(PATH_[]translit($1, [-a-z.], [_A-Z_]), $1,, $2[]ifelse($2,,,:)/usr/bin:/bin:/sbin:/usr/sbin:/usr/etc:/usr/libexec:/usr/ucb:/usr/bsd:/usr/5bin:$PATH:/usr/local/bin:/usr/local/sbin:/usr/X11R6/bin) if test "$PATH_[]translit($1, [-a-z.], [_A-Z_])"; then AC_DEFINE_UNQUOTED(PATH_[]translit($1, [-a-z.], [_A-Z_]), "$PATH_[]translit($1, [-a-z.], [_A-Z_])", Full path of $1 command) fi]) dnl dnl File path to cpp dnl AC_DEFUN([SFS_PATH_CPP], [AC_PATH_PROG(_PATH_CPP, cpp,, /usr/ccs/bin:/usr/bin:/bin:/sbin:/usr/sbin:/usr/etc:/usr/libexec:/lib:/usr/lib:/usr/ucb:/usr/bsd:/usr/5bin:$PATH:/usr/local/bin:/usr/local/sbin:/usr/X11R6/bin) if test -z "$_PATH_CPP"; then if test "$GCC" = yes; then _PATH_CPP=`$CC -print-prog-name=cpp` else _PATH_CPP=`gcc -print-prog-name=cpp 2> /dev/null` fi fi test -x "$_PATH_CPP" || unset _PATH_CPP if test -z "$_PATH_CPP"; then AC_MSG_ERROR(Cannot find path for cpp) fi AC_DEFINE_UNQUOTED(PATH_CPP, "$_PATH_CPP", Path for the C preprocessor command) ]) dnl dnl How to get BSD-like df output dnl AC_DEFUN([SFS_PATH_DF], [SFS_PATH_PROG(df, /usr/ucb:/usr/bsd:/usr/local/bin) AC_CACHE_CHECK(if [$PATH_DF] needs -k for BSD-formatted output, sfs_cv_df_dash_k, sfs_cv_df_dash_k=no [test "`$PATH_DF . | sed -e '2,$d;/Mounted on/d'`" \ && test "`$PATH_DF -k . | sed -ne '2,$d;/Mounted on/p'`" \ && sfs_cv_df_dash_k=yes]) if test $sfs_cv_df_dash_k = yes; then AC_DEFINE(DF_NEEDS_DASH_K, 1, Define if you must run \"df -k\" to get BSD-formatted output) fi]) dnl dnl Check for declarations dnl SFS_CHECK_DECL(symbol, headers-to-try, headers-to-include) dnl AC_DEFUN([SFS_CHECK_DECL], [AC_CACHE_CHECK(for a declaration of $1, sfs_cv_$1_decl, dnl for hdr in [patsubst(builtin(shift, $@), [,], [ ])]; do for hdr in $2; do if test -z "${sfs_cv_$1_decl}"; then dnl AC_HEADER_EGREP($1, $hdr, sfs_cv_$1_decl=yes) AC_TRY_COMPILE( patsubst($3, [\([^ ]+\) *], [#include <\1> ])[#include <$hdr>], &$1;, sfs_cv_$1_decl=yes) fi done test -z "${sfs_cv_$1_decl+set}" && sfs_cv_$1_decl=no) if test "$sfs_cv_$1_decl" = no; then AC_DEFINE_UNQUOTED(NEED_[]translit($1, [a-z], [A-Z])_DECL, 1, Define if system headers do not declare $1.) fi]) dnl dnl Check if lsof keeps a device cache dnl AC_DEFUN([SFS_LSOF_DEVCACHE], [if test "$PATH_LSOF"; then AC_CACHE_CHECK(if lsof supports a device cache, sfs_cv_lsof_devcache, if $PATH_LSOF -h 2>&1 | fgrep -e -D > /dev/null; then sfs_cv_lsof_devcache=yes else sfs_cv_lsof_devcache=no fi) if test "$sfs_cv_lsof_devcache" = yes; then AC_DEFINE(LSOF_DEVCACHE, 1, Define is lsof supports the -D option) fi fi]) dnl dnl Posix time subroutine dnl AC_DEFUN([SFS_TIME_CHECK], [AC_CACHE_CHECK($3, sfs_cv_time_check_$1, AC_TRY_COMPILE([ #ifdef TIME_WITH_SYS_TIME # include # include #elif defined (HAVE_SYS_TIME_H) # include #else /* !TIME_WITH_SYS_TIME && !HAVE_SYS_TIME_H */ # include #endif /* !TIME_WITH_SYS_TIME && !HAVE_SYS_TIME_H */ ], $2, sfs_cv_time_check_$1=yes, sfs_cv_time_check_$1=no)) if test "$sfs_cv_time_check_$1" = yes; then AC_DEFINE($1, 1, $4) fi]) dnl dnl Posix time stuff dnl AC_DEFUN([SFS_TIMESPEC], [AC_CHECK_HEADERS(sys/time.h) AC_HEADER_TIME AC_CHECK_FUNCS(clock_gettime) SFS_TIME_CHECK(HAVE_CLOCK_GETTIME_DECL, int (*x) () = &clock_gettime;, for a declaration of clock_gettime, Define if system headers declare clock_gettime.) SFS_TIME_CHECK(HAVE_TIMESPEC, int x = sizeof (struct timespec), for struct timespec, Define if sys/time.h defines a struct timespec.) dnl AC_EGREP_HEADER(clock_gettime, sys/time.h, dnl AC_DEFINE(HAVE_CLOCK_GETTIME_DECL, 1, dnl Define if system header files declare clock_gettime.)) dnl AC_EGREP_HEADER(timespec, sys/time.h, dnl AC_DEFINE(HAVE_TIMESPEC, 1, dnl Define if sys/time.h defines a struct timespec.)) ]) dnl dnl Find the crypt function dnl AC_DEFUN([SFS_FIND_CRYPT], [AC_SUBST(LIBCRYPT) AC_CHECK_FUNC(crypt) if test $ac_cv_func_crypt = no; then AC_CHECK_LIB(crypt, crypt, LIBCRYPT="-lcrypt") fi ]) dnl dnl Find the setusercontext function dnl AC_DEFUN([SFS_CHECK_SETUSERCONTEXT], [AC_SUBST(SETUSERCONTEXTLIB) AC_CHECK_FUNC(setusercontext) if test "$ac_cv_func_setusercontext" = no; then AC_CHECK_LIB(setusercontext, util, SETUSERCONTEXTLIB="-lutil") fi if test "$ac_cv_func_setusercontext" = yes; then AC_CHECK_HEADERS(login_cap.h) AC_DEFINE(HAVE_SETUSERCONTEXT, 1, Define if you have the setusercontext function) fi ]) dnl dnl Find pty functions dnl AC_DEFUN([SFS_PTYLIB], [AC_SUBST(PTYLIB) AC_CHECK_FUNCS(_getpty) AC_CHECK_FUNCS(openpty) if test $ac_cv_func_openpty = no; then AC_CHECK_LIB(util, openpty, PTYLIB="-lutil" AC_DEFINE(HAVE_OPENPTY, 1, Define if you have the openpty function.)) fi if test "$ac_cv_func_openpty" = yes -o "$ac_cv_lib_util_openpty" = yes; then AC_CHECK_HEADERS(util.h libutil.h) fi AC_CHECK_HEADERS(pty.h) AC_CACHE_CHECK(for BSD-style utmp slots, ac_cv_have_ttyent, AC_EGREP_HEADER(getttyent, ttyent.h, ac_cv_have_ttyent=yes, ac_cv_have_ttyent=no)) if test "$ac_cv_have_ttyent" = yes; then AC_DEFINE(USE_TTYENT, 1, Define if utmp must be managed with BSD-style ttyent functions) fi AC_MSG_CHECKING(for pseudo ttys) if test -c /dev/ptmx && test -c /dev/pts/0 then AC_DEFINE(HAVE_DEV_PTMX, 1, Define if you have SYSV-style /dev/ptmx and /dev/pts/.) AC_MSG_RESULT(streams ptys) else if test -c /dev/pts && test -c /dev/ptc then AC_DEFINE(HAVE_DEV_PTS_AND_PTC, 1, Define if you have /dev/pts and /dev/ptc devices (as in AIX).) AC_MSG_RESULT(/dev/pts and /dev/ptc) else AC_MSG_RESULT(bsd-style ptys) fi fi]) dnl dnl SFS_TRY_RESOLV_LIB(library) dnl see if -llibrary is needed to get res_mkquery dnl AC_DEFUN([SFS_TRY_RESOLV_LIB], [reslib="$1" if test -z "$reslib"; then resdesc="standard C library" else resdesc="lib$reslib" fi AC_CACHE_CHECK(for resolver functions in [$resdesc], sfs_cv_reslib_lib$1, [sfs_try_resolv_lib_save_LIBS="$LIBS" if test x"$reslib" != x; then LIBS="$LIBS -l$reslib" fi AC_LINK_IFELSE([ #include "confdefs.h" #include #include #include #include #if HAVE_ARPA_NAMESER_COMPAT_H #include #else /* !HAVE_ARPA_NAMESER_COMPAT_H */ #include #endif /* !HAVE_ARPA_NAMESER_COMPAT_H */ #include int main (int argc, char **argv) { res_mkquery (0, 0, 0, 0, 0, 0, 0, 0, 0); return 0; }], sfs_cv_reslib_lib$1=yes, sfs_cv_reslib_lib$1=no) LIBS="$sfs_try_resolv_lib_save_LIBS"]) if test "$sfs_cv_reslib_lib$1" = yes -a "$reslib"; then LIBS="$LIBS -l$reslib" fi ]) dnl dnl Use -lresolv only if we need it dnl AC_DEFUN([SFS_FIND_RESOLV], [AC_CHECK_HEADERS(arpa/nameser_compat.h) if test "$ac_cv_header_arpa_nameser_compat_h" = yes; then nameser_header=arpa/nameser_compat.h else nameser_header=arpa/nameser.h fi dnl AC_CHECK_FUNC(res_mkquery) dnl if test "$ac_cv_func_res_mkquery" != yes; then dnl AC_CHECK_LIB(resolv, res_mkquery) dnl if test "$ac_cv_lib_resolv_res_mkquery" = no; then dnl AC_CHECK_LIB(resolv, __res_mkquery) dnl fi dnl fi SFS_TRY_RESOLV_LIB([]) if test "$sfs_cv_reslib_lib" = no; then SFS_TRY_RESOLV_LIB(resolv) fi dnl See if the resolv functions are actually declared SFS_CHECK_DECL(res_init, resolv.h, sys/types.h sys/socket.h netinet/in.h $nameser_header) SFS_CHECK_DECL(res_mkquery, resolv.h, sys/types.h sys/socket.h netinet/in.h $nameser_header) SFS_CHECK_DECL(dn_skipname, resolv.h, sys/types.h sys/socket.h netinet/in.h $nameser_header) SFS_CHECK_DECL(dn_expand, resolv.h, sys/types.h sys/socket.h netinet/in.h $nameser_header) ]) dnl dnl Check if first element in grouplist is egid dnl AC_DEFUN([SFS_CHECK_EGID_IN_GROUPLIST], [AC_TYPE_GETGROUPS AC_CACHE_CHECK(if egid is first element of grouplist, sfs_cv_egid_in_grouplist, AC_TRY_RUN([changequote changequote([[,]]) #include #include #include #include #include "confdefs.h" static int getint (void *_p) { unsigned char *p = _p; return p[0]<<24 | p[1]<<16 | p[2]<<8 | p[3]; } int main (int argc, char **argv) { AUTH *a; GETGROUPS_T gids[24]; int n, xn; char buf[408]; char *p; XDR x; /* Must hard-code OSes with egid in grouplist *and* broken RPC lib */ #if __FreeBSD__ || __APPLE__ return 0; #endif n = getgroups (24, gids); if (n <= 0) return 1; a = authunix_create_default (); xdrmem_create (&x, buf, sizeof (buf), XDR_ENCODE); if (!auth_marshall (a, &x)) return 1; if (getint (buf) != AUTH_UNIX) return 1; p = buf + 12; /* Skip auth flavor, length, timestamp */ p += getint (p) + 7 & ~3; /* Skip machine name */ p += 8; /* Skip uid & gid */ xn = getint (p); /* Length of grouplist in auth_unix */ return n != xn + 1; } changequote([,])], sfs_cv_egid_in_grouplist=yes, sfs_cv_egid_in_grouplist=no)) if test $sfs_cv_egid_in_grouplist = yes; then AC_DEFINE(HAVE_EGID_IN_GROUPLIST, 1, Define if the first element of a grouplist is the effective gid) fi]) dnl dnl Check for struct passwd fields dnl AC_DEFUN([SFS_PASSWD_FIELD], [AC_CACHE_CHECK(for $1 in struct passwd, sfs_cv_passwd_$1, AC_TRY_COMPILE([ #include #include ], [ struct passwd *pw; pw->$1; ], sfs_cv_passwd_$1=yes, sfs_cv_passwd_$1=no)) if test "$sfs_cv_passwd_$1" = yes; then AC_DEFINE(HAVE_PASSWD_[]translit($1, [a-z ], [A-Z_]), 1, Define if struct passwd has $1 field) fi]) dnl dnl Check if putenv copies arguments dnl AC_DEFUN([SFS_PUTENV_COPY], [AC_CACHE_CHECK(if putenv() copies its argument, sfs_cv_putenv_copy, AC_TRY_RUN([ changequote`'changequote([[,]]) #include char var[] = "V=0"; int main (int argc, char **argv) { char *v; putenv (var); var[2] = '1'; v = getenv ("V"); return *v != '0'; } changequote([,])], sfs_cv_putenv_copy=yes, sfs_cv_putenv_copy=no, sfs_cv_putenv_copy=no) ) if test $sfs_cv_putenv_copy = yes; then AC_DEFINE(PUTENV_COPIES_ARGUMENT, 1, Define if putenv makes a copy of its argument) fi]) dnl dnl Check for wide select dnl AC_DEFUN([SFS_CHECK_WIDE_SELECT], [AC_CACHE_CHECK(for wide select, sfs_cv_wideselect, fdlim_h=${srcdir}/fdlim.h test -f ${srcdir}/async/fdlim.h && fdlim_h=${srcdir}/async/fdlim.h test -f ${srcdir}/libasync/fdlim.h && fdlim_h=${srcdir}/libasync/fdlim.h AC_TRY_RUN([changequote changequote([[,]]) #include #include #include #include "${fdlim_h}" struct timeval ztv; int main () { int pfd[2]; int rfd, wfd; int maxfd; int i; fd_set *rfdsp, *wfdsp; maxfd = fdlim_get (1); fdlim_set (maxfd, 1); maxfd = fdlim_get (0); if (maxfd <= FD_SETSIZE) { printf ("[small fd limit anyway] "); exit (1); } if (pipe (pfd) < 0) exit (1); #ifdef F_DUPFD if ((rfd = fcntl (pfd[0], F_DUPFD, maxfd - 2)) < 0) exit (1); if ((wfd = fcntl (pfd[1], F_DUPFD, maxfd - 1)) < 0) exit (1); #else /* !F_DUPFD */ if ((rfd = dup2 (pfd[0], maxfd - 2)) < 0) exit (1); if ((wfd = dup2 (pfd[1], maxfd - 1)) < 0) exit (1); #endif /* !F_DUPFD */ rfdsp = malloc (1 + (maxfd/8)); for (i = 0; i < 1 + (maxfd/8); i++) ((char *) rfdsp)[i] = '\0'; wfdsp = malloc (1 + (maxfd/8)); for (i = 0; i < 1 + (maxfd/8); i++) ((char *) wfdsp)[i] = '\0'; FD_SET (rfd, rfdsp); FD_SET (wfd, wfdsp); if (select (maxfd, rfdsp, wfdsp, NULL, &ztv) < 0) exit (1); if (FD_ISSET (wfd, wfdsp) && !FD_ISSET (rfd, rfdsp)) exit (0); else exit (1); } changequote([,])], sfs_cv_wideselect=yes, sfs_cv_wideselect=no, sfs_cv_wideselect=no)) if test $sfs_cv_wideselect = yes; then AC_DEFINE(HAVE_WIDE_SELECT, 1, Define if select can take file descriptors >= FD_SETSIZE) fi]) dnl dnl Check for 64-bit off_t dnl AC_DEFUN([SFS_CHECK_OFF_T_64], [AC_CACHE_CHECK(for 64-bit off_t, sfs_cv_off_t_64, AC_TRY_COMPILE([ #include #include ],[ switch (0) case 0: case (sizeof (off_t) <= 4):; ], sfs_cv_off_t_64=no, sfs_cv_off_t_64=yes)) if test $sfs_cv_off_t_64 = yes; then AC_DEFINE(HAVE_OFF_T_64, 1, Define if off_t is 64 bits wide.) fi]) dnl dnl Check for type dnl AC_DEFUN([SFS_CHECK_TYPE], [AC_CACHE_CHECK(for $1, sfs_cv_type_[]translit($1, [ ], [_]), AC_TRY_COMPILE([ #include #include #include #include #ifdef HAVE_RPC_RPC_H #include #endif $2 ],[ sizeof($1); ], sfs_cv_type_[]translit($1, [ ], [_])=yes, sfs_cv_type_[]translit($1, [ ], [_])=no)) if test $sfs_cv_type_[]translit($1, [ ], [_]) = yes; then AC_DEFINE(HAVE_[]translit($1, [a-z ], [A-Z_]), 1, Define if system headers declare a $1 type.) fi]) dnl dnl Check if system defines u_int64_t as an unsigned long long dnl AC_DEFUN([SFS_CHECK_U_INT64], [AC_CHECK_SIZEOF(long, 4) AC_CHECK_SIZEOF(long long, 0) SFS_CHECK_TYPE(u_int64_t) AC_CACHE_CHECK(whether u_int64_t is an unsigned long long, sfs_cv_u_int64_t_is_long_long, if test 8 -gt "$ac_cv_sizeof_long"; then sfs_cv_u_int64_t_is_long_long=yes elif test yes != "$sfs_cv_type_u_int64_t"; then sfs_cv_u_int64_t_is_long_long=yes else AC_COMPILE_IFELSE([ #include #include #include #include #ifdef HAVE_RPC_RPC_H #include #endif void f (u_int64_t val); void f (unsigned long long val) { } ], sfs_cv_u_int64_t_is_long_long=yes, sfs_cv_u_int64_t_is_long_long=no) fi) if test yes = "$sfs_cv_u_int64_t_is_long_long"; then AC_DEFINE(U_INT64_T_IS_LONG_LONG, 1, Define if system header files typedef u_int64_t as unsigned long long) fi]) dnl dnl Check for struct cmsghdr (for passing file descriptors) dnl AC_DEFUN([SFS_CHECK_FDPASS], [ AC_CACHE_CHECK(for fd passing with msg_accrights in msghdr, sfs_cv_accrights, AC_TRY_COMPILE([ #include #include ],[ struct msghdr mh; mh.msg_accrights = 0; ], sfs_cv_accrights=yes, sfs_cv_accrights=no)) AC_CACHE_CHECK(for fd passing with struct cmsghdr, sfs_cv_cmsghdr, if test "$sfs_cv_accrights" != "yes"; then AC_TRY_COMPILE([ #include #include ],[ struct msghdr mh; struct cmsghdr cmh; mh.msg_control = (void *) &cmh; ], sfs_cv_cmsghdr=yes, sfs_cv_cmsghdr=no) else sfs_cv_cmsghdr=no fi) if test $sfs_cv_accrights = yes; then AC_DEFINE(HAVE_ACCRIGHTS, 1, Define if msghdr has msg_accrights field for passing file descriptors.) fi if test $sfs_cv_cmsghdr = yes; then AC_DEFINE(HAVE_CMSGHDR, 1, Define if system has cmsghdr structure for passing file descriptors.) fi]) dnl dnl Check for sa_len in struct sockaddrs dnl AC_DEFUN([SFS_CHECK_SA_LEN], [AC_CACHE_CHECK(for sa_len in struct sockaddr, sfs_cv_sa_len, AC_TRY_COMPILE([ #include #include ],[ struct sockaddr sa; sa.sa_len = 0; ], sfs_cv_sa_len=yes, sfs_cv_sa_len=no)) if test $sfs_cv_sa_len = yes; then AC_DEFINE(HAVE_SA_LEN, 1, Define if struct sockaddr has sa_len field.) fi]) dnl dnl Check for sockaddr_storage dnl AC_DEFUN([SFS_CHECK_SOCKADDR_STORAGE], [SFS_CHECK_TYPE(struct sockaddr_storage) AC_CACHE_CHECK(for __ss_len in sockaddr_storage, sfs_cv_ss_len_underscores, AC_TRY_COMPILE([ #include #include ],[ struct sockaddr_storage ss; ss.__ss_len = 0; ], sfs_cv_ss_len_underscores=yes, sfs_cv_ss_len_underscores=no)) if test $sfs_cv_ss_len_underscores = yes; then AC_DEFINE(HAVE_SS_LEN_UNDERSCORES, 1, Define if struct sockaddr_storage has __ss_len field, not ss_len) fi]) dnl dnl Check something about the nfs_args field dnl AC_DEFUN([SFS_TRY_NFSARG_FIELD], [AC_TRY_COMPILE([ #include "${srcdir}/nfsconf.h" ],[ struct nfs_args na; $1; ], $2, $3)]) dnl dnl Check a particular field in nfs_args dnl AC_DEFUN([SFS_CHECK_NFSMNT_FIELD], [AC_CACHE_CHECK(for $1 in nfs_args structure, sfs_cv_nfsmnt_$1, SFS_TRY_NFSARG_FIELD(na.$1, sfs_cv_nfsmnt_$1=yes, sfs_cv_nfsmnt_$1=no)) if test $sfs_cv_nfsmnt_$1 = yes; then AC_DEFINE(HAVE_NFSMNT_[]translit($1, [a-z], [A-Z]), 1, Define if the nfs_args structure has a $1 field.) fi]) dnl dnl Check if nfs_args hostname field is an array dnl AC_DEFUN([SFS_CHECK_NFSARG_HOSTNAME_ARRAY], [AC_CACHE_CHECK(if nfs_args hostname field is an array, sfs_cv_nfs_hostarray, SFS_TRY_NFSARG_FIELD(na.hostname = 0, sfs_cv_nfs_hostarray=no, sfs_cv_nfs_hostarray=yes)) if test $sfs_cv_nfs_hostarray = yes; then AC_DEFINE(HAVE_NFSARG_HOSTNAME_ARRAY, 1, [The hostname field of nfs_arg is an array]) fi]) dnl dnl Check if addr field is a pointer or not dnl AC_DEFUN([SFS_CHECK_NFSARG_ADDR_PTR], [AC_CHECK_HEADERS(tiuser.h) AC_CACHE_CHECK(if nfs_args addr field is a pointer, sfs_cv_nfsmnt_addr_ptr, SFS_TRY_NFSARG_FIELD(na.addr = (void *) 0, sfs_cv_nfsmnt_addr_ptr=yes, sfs_cv_nfsmnt_addr_ptr=no)) if test $sfs_cv_nfsmnt_addr_ptr = yes; then AC_DEFINE(HAVE_NFSARG_ADDR_PTR, 1, [The addr field of nfs_arg is a pointer]) AC_CACHE_CHECK(if nfs_args addr is a netbuf *, sfs_cv_nfsmnt_addr_netbuf, SFS_TRY_NFSARG_FIELD(struct netbuf nb; *na.addr = nb, sfs_cv_nfsmnt_addr_netbuf=yes, sfs_cv_nfsmnt_addr_netbuf=no)) if test $sfs_cv_nfsmnt_addr_netbuf = yes; then AC_DEFINE(HAVE_NFSARG_ADDR_NETBUF, 1, [If the nfs_arg addr field is a netbuf pointer]) fi fi]) dnl dnl Check for SVR4-like nfs_fh3 structure dnl AC_DEFUN([SFS_CHECK_FH3_SVR4], [if test "$sfs_cv_nfsmnt_fhsize" != yes; then AC_CACHE_CHECK(for SVR4-like struct nfs_fh3, sfs_cv_fh3_svr4, AC_TRY_COMPILE([#include "${srcdir}/nfsconf.h"], [ struct nfs_fh3 fh; switch (0) case 0: case sizeof (fh.fh3_u.data) == 64:; ], sfs_cv_fh3_svr4=yes, sfs_cv_fh3_svr4=no)) if test $sfs_cv_fh3_svr4 = yes; then AC_DEFINE(HAVE_SVR4_FH3, 1, [The the fh field of the nfs_arg structure points to an SVR4 nfs_fh3]) fi fi]) dnl dnl Check for 2 argument unmount dnl AC_DEFUN([SFS_CHECK_UNMOUNT_FLAGS], [AC_CACHE_CHECK(for a 2 argument unmount, sfs_cv_umount_flags, AC_TRY_COMPILE([ #include #include ],[ #ifdef HAVE_UNMOUNT unmount #else /* !HAVE_UNMOUNT */ umount #endif /* !HAVE_UNMOUNT */ (0); ], sfs_cv_umount_flags=no, sfs_cv_umount_flags=yes)) if test $sfs_cv_umount_flags = yes; then AC_DEFINE(UNMOUNT_FLAGS, 1, Define if the unmount system call has 2 arguments.) else AC_CHECK_FUNCS(umount2) fi]) dnl dnl Check if we can find the nfs_args structure dnl AC_DEFUN([SFS_CHECK_NFSMNT], [AC_CHECK_FUNCS(vfsmount unmount) AC_CHECK_HEADERS(nfs/nfsproto.h, [], [], [#include #include #include ]) need_nfs_nfs_h=no AC_EGREP_HEADER(nfs_args, sys/mount.h,, AC_EGREP_HEADER(nfs_args, nfs/mount.h, AC_DEFINE(NEED_NFS_MOUNT_H, 1, [The nfs_args structure is in ])) AC_EGREP_HEADER(nfs_args, nfs/nfsmount.h, AC_DEFINE(NEED_NFS_NFSMOUNT_H, 1, [The nfs_args structure is in ])) AC_EGREP_HEADER(nfs_args, nfs/nfs.h, AC_DEFINE(NEED_NFS_NFS_H, 1, [The nfs_args structure is in ]) need_nfs_nfs_h=yes)) AC_CACHE_CHECK(for nfs_args mount structure, sfs_cv_nfsmnt_ok, SFS_TRY_NFSARG_FIELD(, sfs_cv_nfsmnt_ok=yes, sfs_cv_nfsmnt_ok=no)) if test $sfs_cv_nfsmnt_ok = no; then AC_MSG_ERROR([Could not find NFS mount argument structure!]) fi if test "$need_nfs_nfs_h" = no; then AC_EGREP_HEADER(nfs_fh3, nfs/nfs.h, AC_DEFINE(NEED_NFS_NFS_H, 1, [The nfs_args structure is in ]) need_nfs_nfs_h=yes) fi AC_CHECK_HEADERS(linux/nfs2.h) SFS_CHECK_NFSMNT_FIELD(addrlen) SFS_CHECK_NFSMNT_FIELD(sotype) SFS_CHECK_NFSMNT_FIELD(proto) SFS_CHECK_NFSMNT_FIELD(fhsize) SFS_CHECK_NFSMNT_FIELD(fd) dnl Check whether we have Linux 2.2 NFS V3 mount structure SFS_CHECK_NFSMNT_FIELD(old_root) dnl Check whether file handle is named "root" or "fh" SFS_CHECK_NFSMNT_FIELD(root) SFS_CHECK_NFSMNT_FIELD(fh) dnl ksh apparently cannot handle this as a compound test. if test "$sfs_cv_nfsmnt_root" = "no"; then if test "$sfs_cv_nfsmnt_fh" = "no"; then AC_MSG_ERROR([Could not find the nfs_args file handle field!]) fi fi AC_CHECK_HEADERS(sys/mntent.h) SFS_CHECK_FH3_SVR4 if test "$sfs_cv_nfsmnt_fh" = yes; then if test "$sfs_cv_fh3_svr4" = yes -o "$sfs_cv_nfsmnt_fhsize" = yes; then AC_DEFINE(HAVE_NFS_V3, 1, [If the system supports NFS 3]) fi elif test "$sfs_cv_nfsmnt_old_root" = yes; then AC_DEFINE(HAVE_NFS_V3, 1, [If the system supports NFS 3]) fi SFS_CHECK_NFSARG_HOSTNAME_ARRAY SFS_CHECK_NFSARG_ADDR_PTR SFS_CHECK_UNMOUNT_FLAGS]) dnl dnl Use -ldb only if we need it. dnl AC_DEFUN([SFS_FIND_DB], [AC_CHECK_FUNC(dbopen) if test $ac_cv_func_dbopen = no; then AC_CHECK_LIB(db, dbopen) if test $ac_cv_lib_db_dbopen = no; then AC_MSG_ERROR([Could not find library for dbopen!]) fi fi ]) dnl dnl Check something about the stat structure dnl AC_DEFUN([SFS_TRY_STAT_FIELD], [AC_TRY_COMPILE([ #include ],[ struct stat s; $1; ], $2, $3)]) dnl dnl Check for a particular field in stat dnl AC_DEFUN([SFS_CHECK_STAT_FIELD], [AC_CACHE_CHECK(for $1 in stat structure, sfs_cv_stat_$1, SFS_TRY_STAT_FIELD(s.$1, sfs_cv_stat_$1=yes, sfs_cv_stat_$1=no)) if test $sfs_cv_stat_$1 = yes; then AC_DEFINE(SFS_HAVE_STAT_[]translit($1, [a-z], [A-Z]), 1, Define if the stat structure has a $1 field.) fi]) dnl dnl Check whether we can get away with large socket buffers. dnl AC_DEFUN([SFS_CHECK_SOCK_BUF], [AC_CACHE_CHECK(whether socket buffers > 64k are allowed, sfs_cv_large_sock_buf, AC_TRY_RUN([ #include #include int main() { int bigbuf = 0x11000; int s = socket(AF_INET, SOCK_STREAM, 0); if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&bigbuf, sizeof(bigbuf))<0) exit(1); exit(0); } ], sfs_cv_large_sock_buf=yes, sfs_cv_large_sock_buf=no, sfs_cv_large_sock_buf=no)) if test $sfs_cv_large_sock_buf = yes; then AC_DEFINE(SFS_ALLOW_LARGE_BUFFER, 1, Define if SO_SNDBUF/SO_RCVBUF can exceed 64K.) fi]) dnl dnl Test to see if we can bind a port with SO_REUSEADDR when dnl there is a connected TCP socket using the same port number, dnl but the connected socket does not have SO_REUSEADDR set. dnl AC_DEFUN([SFS_CHECK_BSD_REUSEADDR], [AC_CACHE_CHECK(for BSD SO_REUSEADDR semantics, sfs_cv_bsd_reuseaddr, [AC_RUN_IFELSE([changequote changequote([[,]])[[ #include #include #include #include #include #include #include #include #include #include "confdefs.h" #ifndef HAVE_SOCKLEN_T # define socklen_t int #endif /* !HAVE_SOCKLEN_T */ #ifndef bzero # define bzero(a,b) memset((a), 0, (b)) #endif /* !bzero */ int inetsocket (unsigned long addr, int port, int *portp) { int s; struct sockaddr_in sin; int n = 1; bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (port); sin.sin_addr.s_addr = htonl (addr); s = socket (AF_INET, SOCK_STREAM, 0); if (s < 0) { perror ("socket"); exit (2); } if (port && setsockopt (s,SOL_SOCKET, SO_REUSEADDR, &n, sizeof n) < 0) { perror ("SO_REUSEADDR"); exit (2); } if (bind (s, (struct sockaddr *) &sin, sizeof (sin)) < 0) return -1; if (portp) { socklen_t sinlen = sizeof (sin); getsockname (s, (struct sockaddr *) &sin, &sinlen); *portp = ntohs (sin.sin_port); } return s; } int connectlocal (int s, int dport) { struct sockaddr_in sin; bzero (&sin, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_port = htons (dport); sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK); return connect (s, (struct sockaddr *) &sin, sizeof (sin)); } void make_async (int s) { int n; if ((n = fcntl (s, F_GETFL)) < 0 || fcntl (s, F_SETFL, n | O_NONBLOCK) < 0) { perror ("fcntl"); exit (2); } } int main (int argc, char **argv) { int s1, s1p; int c1, c1p; int c2; s1 = inetsocket (INADDR_LOOPBACK, 0, &s1p); listen (s1, 5); c1 = inetsocket (INADDR_LOOPBACK, 0, &c1p); make_async (c1); if (connectlocal (c1, s1p) < 0) { if (errno == EINPROGRESS) { struct sockaddr_in sin; socklen_t sinlen = sizeof (sin); sin.sin_family = AF_INET; accept (s1, (struct sockaddr *) &sin, &sinlen); } else { perror ("connect"); exit (2); } } c2 = inetsocket (INADDR_ANY, c1p, NULL); exit (c2 < 0); } ]]changequote([,])], sfs_cv_bsd_reuseaddr=yes, sfs_cv_bsd_reuseaddr=no, sfs_cv_bsd_reuseaddr=no)]) if test "$sfs_cv_bsd_reuseaddr" = yes; then AC_DEFINE(HAVE_BSD_REUSEADDR, 1, Define if SO_REUSEADDR allows same user to bind non-SO_REUSEADDR port) fi]) dnl dnl Find pthreads dnl AC_DEFUN([SFS_FIND_PTHREADS], [AC_ARG_WITH(pthreads, --with-pthreads=DIR Specify location of pthreads) ac_save_CFLAGS=$CFLAGS ac_save_LIBS=$LIBS dirs="$with_pthreads ${prefix} ${prefix}/pthreads" dirs="$dirs /usr/local /usr/local/pthreads" AC_CACHE_CHECK(for pthread.h, sfs_cv_pthread_h, [for dir in " " $dirs; do iflags="-I${dir}/include" CFLAGS="${ac_save_CFLAGS} $iflags" AC_TRY_COMPILE([#include ], 0, sfs_cv_pthread_h="${iflags}"; break) done]) if test -z "${sfs_cv_pthread_h+set}"; then AC_MSG_ERROR("Can\'t find pthread.h anywhere") fi AC_CACHE_CHECK(for libpthread, sfs_cv_libpthread, [for dir in "" " " $dirs; do case $dir in "") lflags=" " ;; " ") lflags="-lpthread" ;; *) lflags="-L${dir}/lib -lpthread" ;; esac LIBS="$ac_save_LIBS $lflags" AC_TRY_LINK([#include ], pthread_create (0, 0, 0, 0);, sfs_cv_libpthread=$lflags; break) done]) if test -z ${sfs_cv_libpthread+set}; then AC_MSG_ERROR("Can\'t find libpthread anywhere") fi CFLAGS=$ac_save_CFLAGS CPPFLAGS="$CPPFLAGS $sfs_cv_pthread_h" LIBS="$ac_save_LIBS $sfs_cv_libpthread"]) dnl dnl Find GMP dnl AC_DEFUN([SFS_GMP], [AC_ARG_WITH(gmp, --with-gmp[[[=/usr/local]]] specify path for gmp) AC_SUBST(GMP_DIR) AC_SUBST(LIBGMP) AC_MSG_CHECKING([for GMP library]) test "$with_gmp" = "no" && unset with_gmp if test -z "$with_gmp"; then if test -z "$GMP_DIR"; then for dir in `cd $srcdir && echo gmp*`; do if test -d "$srcdir/$dir"; then GMP_DIR=$dir break fi done fi if test "${with_gmp+set}" != set \ -a "$GMP_DIR" -a -d "$srcdir/$GMP_DIR"; then GMP_DIR=`echo $GMP_DIR | sed -e 's!/$!!'` if test -f "$srcdir/$GMP_DIR/gmp-h.in"; then CPPFLAGS="$CPPFLAGS "'-I$(top_builddir)/'"$GMP_DIR" else CPPFLAGS="$CPPFLAGS "'-I$(top_srcdir)/'"$GMP_DIR" fi #LDFLAGS="$LDFLAGS "'-L$(top_builddir)/'"$GMP_DIR" else GMP_DIR= for dir in "$prefix" /usr/local /usr; do if test \( -f $dir/lib/libgmp.a -o -f $dir/lib/libgmp.la \) \ -a \( -f $dir/include/gmp.h -o -f $dir/include/gmp3/gmp.h \ -o -f $dir/include/gmp2/gmp.h \); then with_gmp=$dir break fi done if test -z "$with_gmp"; then AC_MSG_ERROR([Could not find GMP library]) fi test "$with_gmp" = /usr -a -f /usr/include/gmp.h && unset with_gmp fi fi if test "$with_gmp"; then unset GMP_DIR if test -f ${with_gmp}/include/gmp.h; then test "${with_gmp}" = /usr \ || CPPFLAGS="$CPPFLAGS -I${with_gmp}/include" elif test -f ${with_gmp}/include/gmp3/gmp.h; then CPPFLAGS="$CPPFLAGS -I${with_gmp}/include/gmp3" elif test -f ${with_gmp}/include/gmp2/gmp.h; then CPPFLAGS="$CPPFLAGS -I${with_gmp}/include/gmp2" else AC_MSG_ERROR([Could not find gmp.h header]) fi #LDFLAGS="$LDFLAGS -L${with_gmp}/lib" #LIBGMP=-lgmp if test -f "${with_gmp}/lib/libgmp.la"; then LIBGMP="${with_gmp}/lib/libgmp.la" else LIBGMP="${with_gmp}/lib/libgmp.a" fi AC_MSG_RESULT([$LIBGMP]) elif test "$GMP_DIR"; then export GMP_DIR AC_MSG_RESULT([using distribution in $GMP_DIR subdirectory]) LIBGMP='$(top_builddir)/'"$GMP_DIR/libgmp.la" else AC_MSG_RESULT(yes) if test -f /usr/lib/libgmp.la; then LIBGMP=/usr/lib/libgmp.la elif test -f /usr/lib/libgmp.a; then # FreeBSD (among others) has a broken gmp shared library LIBGMP=/usr/lib/libgmp.a else LIBGMP=-lgmp fi fi AC_CONFIG_SUBDIRS($GMP_DIR) ac_save_CFLAGS="$CFLAGS" if test "$GMP_DIR"; then if test -f "${srcdir}/${GMP_DIR}"/gmp-h.in; then CFLAGS="$CFLAGS -I${srcdir}/${GMP_DIR}" else CFLAGS="$CFLAGS -I${builddir}/${GMP_DIR}" fi fi AC_CACHE_CHECK(for overloaded C++ operators in gmp.h, sfs_cv_gmp_cxx_ops, if test -f "${srcdir}/${GMP_DIR}"/gmp-h.in; then # More recent versions of GMP all have this sfs_cv_gmp_cxx_ops=yes else AC_EGREP_CPP(operator<<, [#define __cplusplus 1 #include ], sfs_cv_gmp_cxx_ops=yes, sfs_cv_gmp_cxx_ops=no) fi) test "$sfs_cv_gmp_cxx_ops" = "yes" && AC_DEFINE([HAVE_GMP_CXX_OPS], 1, [Define if gmp.h overloads C++ operators]) AC_CACHE_CHECK(for mpz_xor, sfs_cv_have_mpz_xor, unset sfs_cv_have_mpz_xor if test "$GMP_DIR"; then sfs_cv_have_mpz_xor=yes else AC_EGREP_HEADER(mpz_xor, [gmp.h], sfs_cv_have_mpz_xor=yes) fi) test "$sfs_cv_have_mpz_xor" && AC_DEFINE([HAVE_MPZ_XOR], 1, [Define if you have mpz_xor in your GMP library.]) AC_CACHE_CHECK(size of GMP mp_limb_t, sfs_cv_mp_limb_t_size, sfs_cv_mp_limb_t_size=no for size in 2 4 8; do AC_TRY_COMPILE([#include ], [switch (0) case 0: case (sizeof (mp_limb_t) == $size):;], sfs_cv_mp_limb_t_size=$size; break) done) CFLAGS="$ac_save_CFLAGS" test "$sfs_cv_mp_limb_t_size" = no \ && AC_MSG_ERROR(Could not determine size of mp_limb_t.) AC_DEFINE_UNQUOTED(GMP_LIMB_SIZE, $sfs_cv_mp_limb_t_size, Define to be the size of GMP's mp_limb_t type.)]) dnl dnl dnl dnl Find BekeleyDB 3 dnl dnl dnl ac_defun(SFS_DB3, dnl [AC_ARG_WITH(db3, dnl --with-db3[[=/usr/local]] specify path for BerkeleyDB-3) dnl AC_SUBST(DB3_DIR) dnl AC_CONFIG_SUBDIRS($DB3_DIR) dnl AC_SUBST(DB3_LIB) dnl unset DB3_LIB dnl dnl DB3_DIR=`cd $srcdir && echo db-3.*/dist/` dnl if test -d "$srcdir/$DB3_DIR"; then dnl DB3_DIR=`echo $DB3_DIR | sed -e 's!/$!!'` dnl else dnl unset DB3_DIR dnl fi dnl dnl if test ! "${with_db3+set}"; then dnl if test "$DB3_DIR"; then dnl with_db3=yes dnl else dnl with_db3=no dnl fi dnl fi dnl dnl if test "$with_db3" != no; then dnl AC_MSG_CHECKING([for DB3 library]) dnl if test "$DB3_DIR" -a "$with_db3" = yes; then dnl CPPFLAGS="$CPPFLAGS "'-I$(top_builddir)/'"$DB3_DIR" dnl DB3_LIB='-L$(top_builddir)/'"$DB3_DIR -ldb" dnl AC_MSG_RESULT([using distribution in $DB3_DIR subdirectory]) dnl else dnl libdbrx='^libdb-?([[3.-]].*)?.(la|so|a)$' dnl libdbrxla='^libdb-?([[3.-]].*)?.la$' dnl libdbrxso='^libdb-?([[3.-]].*)?.so$' dnl libdbrxa='^libdb-?([[3.-]].*)?.a$' dnl if test "$with_db3" = yes; then dnl for dir in "$prefix/BerkeleyDB.3.1" /usr/local/BerkeleyDB.3.1 \ dnl "$prefix/BerkeleyDB.3.0" /usr/local/BerkeleyDB.3.0 \ dnl /usr "$prefix" /usr/local; do dnl test -f $dir/include/db.h -o -f $dir/include/db3.h \ dnl -o -f $dir/include/db3/db.h || continue dnl if test -f $dir/lib/libdb.a \ dnl || ls $dir/lib | egrep "$libdbrx" >/dev/null 2>&1; then dnl with_db3="$dir" dnl break dnl fi dnl done dnl fi dnl dnl if test -f $with_db3/include/db3.h; then dnl AC_DEFINE(HAVE_DB3_H, 1, [Define if BerkeleyDB header is db3.h.]) dnl if test "$with_db3" != /usr; then dnl CPPFLAGS="$CPPFLAGS -I${with_db3}/include" dnl fi dnl elif test -f $with_db3/include/db3/db.h; then dnl if test "$with_db3" != /usr; then dnl CPPFLAGS="$CPPFLAGS -I${with_db3}/include/db3" dnl fi dnl elif test -f $with_db3/include/db.h; then dnl if test "$with_db3" != /usr; then dnl CPPFLAGS="$CPPFLAGS -I${with_db3}/include" dnl fi dnl else dnl AC_MSG_ERROR([Could not find BerkeleyDB library version 3]) dnl fi dnl dnl DB3_LIB=`ls $with_db3/lib | egrep "$libdbrxla" | tail -1` dnl test ! -f "$with_db3/lib/$DB3_LIB" \ dnl && DB3_LIB=`ls $with_db3/lib | egrep "$libdbrxso" | tail -1` dnl test ! -f "$with_db3/lib/$DB3_LIB" \ dnl && DB3_LIB=`ls $with_db3/lib | egrep "$libdbrxa" | tail -1` dnl if test -f "$with_db3/lib/$DB3_LIB"; then dnl DB3_LIB="$with_db3/lib/$DB3_LIB" dnl elif test "$with_db3" = /usr; then dnl with_db3=yes dnl DB3_LIB="-ldb" dnl else dnl DB3_LIB="-L${with_db3}/lib -ldb" dnl fi dnl AC_MSG_RESULT([$with_db3]) dnl fi dnl fi dnl dnl AM_CONDITIONAL(USE_DB3, test "${with_db3}" != no) dnl ]) dnl pushdef([arglist], [ifelse($#, 0, , $#, 1, [[$1]], dnl [[$1] arglist(shift($@))])])dnl dnl dnl SFS_TRY_SLEEPYCAT_VERSION(vers, dir) dnl AC_DEFUN([SFS_TRY_SLEEPYCAT_VERSION], [vers=$1 dir=$2 majvers=`echo $vers | sed -e 's/\..*//'` minvers=`echo $vers | sed -e 's/[^.]*\.//' -e 's/\..*//'` escvers=`echo $vers | sed -e 's/\./\\./g'` catvers=`echo $vers | sed -e 's/\.//g'` : sfs_try_sleepycat_version $vers $dir $majvers $minvers $escvers $catvers unset db_header unset db_library for header in \ $dir/include/db$vers/db.h $dir/include/db$catvers/db.h \ $dir/include/db$majvers/db.h \ $dir/include/db$catvers.h $dir/include/db$majvers.h \ $dir/include/db.h do test -f $header || continue AC_EGREP_CPP(^db_version_is $majvers *\. *$minvers *\$, [#include "$header" db_version_is DB_VERSION_MAJOR.DB_VERSION_MINOR ], db_header=$header; break) done if test "$db_header"; then for vdir in "$dir/lib/db$catvers" "$dir/lib/db$majvers" \ "$dir/lib/db" "$dir/lib" "$dir/lib64" \ "$dir/lib/${host_cpu}-${host_os}" \ "$dir/"`basename "$libdir"` do for library in $vdir/libdb-$vers.la $vdir/libdb$catvers.la \ $vdir/libdb.la $vdir/libdb-$vers.a $vdir/libdb$catvers.a \ $vdir/libdb-$vers.so do if test -f $library; then db_library=$library break 2; fi done done if test -z "$db_library"; then case $db_header in */db.h) test -f $dir/lib/libdb.a && db_library=$dir/lib/libdb.a ;; esac fi if test "$db_library"; then case $db_header in */db.h) CPPFLAGS="$CPPFLAGS -I"`dirname $db_header` ;; *) ln -s $db_header db.h ;; esac case $db_library in *.la) DB_LIB=$db_library ;; *.a) minusl=`echo $db_library | sed -e 's/^.*\/lib\(.*\)\.a$/-l\1/'` DB_LIB=-L`dirname $db_library`" $minusl" ;; */lib*.so.*) minusl=`echo $db_library | sed -e 's/^.*\/lib\(.*\)\.so\..*/-l\1/'` DB_LIB=-L`dirname $db_library`" $minusl" ;; */lib*.so) minusl=`echo $db_library | sed -e 's/^.*\/lib\(.*\)\.so$/-l\1/'` DB_LIB=-L`dirname $db_library`" $minusl" ;; esac fi fi]) dnl dnl SFS_SLEEPYCAT(v1 v2 v3 ..., required) dnl dnl Find BekeleyDB version v1, v2, or v3... dnl required can be "no" if DB is not required dnl AC_DEFUN([SFS_SLEEPYCAT], [AC_ARG_WITH(db, --with-db[[[=/usr/local]]] specify path for BerkeleyDB (from sleepycat.com)) AC_SUBST(DB_DIR) AC_CONFIG_SUBDIRS($DB_DIR) AC_SUBST(DB_LIB) unset DB_LIB rm -f db.h for vers in $1; do DB_DIR=`cd $srcdir && echo db-$vers.*/dist/` if test -d "$srcdir/$DB_DIR"; then DB_DIR=`echo $DB_DIR | sed -e 's!/$!!'` break else unset DB_DIR fi done test -z "${with_db+set}" && with_db=yes AC_MSG_CHECKING(for BerkeleyDB library) if test "$DB_DIR" -a "$with_db" = yes; then CPPFLAGS="$CPPFLAGS "'-I$(top_builddir)/'"$DB_DIR/dist" DB_LIB='$(top_builddir)/'"$DB_DIR/dist/.libs/libdb-*.a" AC_MSG_RESULT([using distribution in $DB_DIR subdirectory]) elif test x"$with_db" != xno; then if test "$with_db" = yes; then for vers in $1; do for dir in "$prefix/BerkeleyDB.$vers" \ "/usr/BerkeleyDB.$vers" \ "/usr/local/BerkeleyDB.$vers" \ $prefix /usr /usr/local; do SFS_TRY_SLEEPYCAT_VERSION($vers, $dir) test -z "$DB_LIB" || break 2 done done else for vers in $1; do SFS_TRY_SLEEPYCAT_VERSION($vers, $with_db) test -z "$DB_LIB" || break done test -z "$DB_LIB" && AC_MSG_ERROR(Cannot find BerkeleyDB in $with_db) fi fi if test x"$DB_LIB" != x; then AC_MSG_RESULT($DB_LIB) USE_DB=yes else AC_MSG_RESULT(no) USE_DB=no if test "$2" != "no"; then AC_MSG_ERROR(Cannot find BerkeleyDB) fi fi AM_CONDITIONAL(USE_DB, test "$USE_DB" = yes) ]) dnl dnl Find OpenSSL dnl AC_DEFUN([SFS_OPENSSL], [AC_SUBST(OPENSSL_DIR) AC_ARG_WITH(openssl, --with-openssl[[=/usr/local/openssl]] Find OpenSSL libraries (DANGER--FOR BENCHMARKING ONLY)) AC_MSG_CHECKING([for OpenSSL]) test "$with_openssl" = "yes" && unset with_openssl unset OPENSSL_DIR if test -z "$with_openssl"; then with_openssl=no for dir in /usr/local/openssl/ /usr/local/ssl/ \ `ls -1d /usr/local/openssl-*/ 2>/dev/null | sed -ne '$p'`; do if test -f $dir/lib/libssl.a -a -f $dir/include/openssl/ssl.h; then with_openssl=`echo $dir | sed -e 's/\/$//'` break fi done fi OPENSSL_DIR="$with_openssl" AC_MSG_RESULT([$with_openssl]) if test "$with_openssl" = no; then dnl if test -z "$with_openssl"; then dnl AC_MSG_ERROR([Could not find OpenSSL libraries]) dnl fi unset OPENSSL_DIR fi]) dnl dnl Use dmalloc if requested dnl AC_DEFUN([SFS_DMALLOC], [ dnl AC_ARG_WITH(small-limits, dnl --with-small-limits Try to trigger memory allocation bugs, dnl CPPFLAGS="$CPPFLAGS -DSMALL_LIMITS" dnl test "${with_dmalloc+set}" = set || with_dmalloc=yes dnl ) AC_CHECK_HEADERS(memory.h) AC_ARG_WITH(dmalloc, --with-dmalloc use debugging malloc from www.dmalloc.com (set MAX_FILE_LEN to 1024 when installing), pref=$prefix test "$pref" = NONE && pref=$ac_default_prefix test "$withval" = yes && withval="${pref}" test "$withval" || withval="${pref}" using_dmalloc=no if test "$withval" != no; then AC_DEFINE(DMALLOC, 1, Define if compiling with dmalloc. ) dnl CPPFLAGS="$CPPFLAGS -DDMALLOC" CPPFLAGS="$CPPFLAGS -I${withval}/include" LIBS="$LIBS -L${withval}/lib -ldmalloc" using_dmalloc=yes fi) AM_CONDITIONAL(DMALLOC, test "$using_dmalloc" = yes) ]) dnl dnl Find perl dnl AC_DEFUN([SFS_PERLINFO], [AC_ARG_WITH(perl, --with-perl=PATH Specify perl executable to use, [case "$withval" in yes|no|"") ;; *) PERL="$withval" ;; esac]) if test -z "$PERL" || test ! -x "$PERL"; then AC_PATH_PROGS(PERL, perl5 perl) fi if test -x "$PERL" && $PERL -e 'require 5.004'; then :; else AC_MSG_ERROR("Can\'t find perl 5.004 or later") fi AC_CACHE_CHECK(for perl includes, sfs_cv_perl_ccopts, sfs_cv_perl_ccopts=`$PERL -MExtUtils::Embed -e ccopts` sfs_cv_perl_ccopts=`echo $sfs_cv_perl_ccopts` ) AC_CACHE_CHECK(for perl libraries, sfs_cv_perl_ldopts, sfs_cv_perl_ldopts=`$PERL -MExtUtils::Embed -e ldopts -- -std` sfs_cv_perl_ldopts=`echo $sfs_cv_perl_ldopts` ) AC_CACHE_CHECK(for perl xsubpp, sfs_cv_perl_xsubpp, sfs_cv_perl_xsubpp="$PERL "`$PERL -MConfig -e 'print qq(\ -I$Config{"installarchlib"} -I$Config{"installprivlib"}\ $Config{"installprivlib"}/ExtUtils/xsubpp\ -typemap $Config{"installprivlib"}/ExtUtils/typemap)'` sfs_cv_perl_xsubpp=`echo $sfs_cv_perl_xsubpp` ) XSUBPP="$sfs_cv_perl_xsubpp" PERL_INC="$sfs_cv_perl_ccopts" PERL_LIB="$sfs_cv_perl_ldopts" PERL_XSI="$PERL -MExtUtils::Embed -e xsinit -- -std" AC_SUBST(PERL) AC_SUBST(PERL_INC) AC_SUBST(PERL_LIB) AC_SUBST(PERL_XSI) AC_SUBST(XSUBPP) ]) dnl dnl Check for perl and for Pod::Man for generating man pages dnl AC_DEFUN([SFS_PERL_POD], [ if test -z "$PERL" || text ! -x "$PERL"; then AC_PATH_PROGS(PERL, perl5 perl) fi AC_PATH_PROGS(POD2MAN, pod2man, pod2man, [$PATH$PATH_SEPARATOR/usr/bin/core_perl]) if test "$PERL"; then AC_CACHE_CHECK(for Pod::Man, sfs_cv_perl_pod_man, $PERL -e '{ require Pod::Man }' >/dev/null 2>&1 if test $? = 0; then sfs_cv_perl_pod_man="yes" else sfs_cv_perl_pod_man="no" fi ) PERL_POD_MAN="$sfs_cv_perl_pod_man" fi AC_SUBST(PERL_POD_MAN) ]) dnl' dnl Various warning flags for gcc. This must go at the very top, dnl right after AC_PROG_CC and AC_PROG_CXX. dnl AC_DEFUN([SFS_WFLAGS], [AC_SUBST(NW) AC_SUBST(WFLAGS) AC_SUBST(CXXWFLAGS) AC_SUBST(DEBUG) AC_SUBST(CXXDEBUG) AC_SUBST(ECFLAGS) AC_SUBST(ECXXFLAGS) AC_SUBST(CXXNOERR) test -z "${CXXWFLAGS+set}" -a "${WFLAGS+set}" && CXXWFLAGS="$WFLAGS" test -z "${CXXDEBUG+set}" -a "${DEBUG+set}" && CXXDEBUG="$DEBUG" test "${DEBUG+set}" || DEBUG="$CFLAGS" export DEBUG test "${CXXDEBUG+set}" || CXXDEBUG="$CXXFLAGS" export CXXDEBUG case $host_os in openbsd*) sfs_gnu_WFLAGS="-ansi -Wall -Wsign-compare -Wchar-subscripts" sfs_gnu_CXXWFLAGS="$sfs_gnu_WFLAGS" ;; linux*|freebsd*) sfs_gnu_WFLAGS="-Wall" sfs_gnu_CXXWFLAGS="$sfs_gnu_WFLAGS" ;; *) sfs_gnu_WFLAGS="-Wall" sfs_gnu_CXXWFLAGS="$sfs_gnu_WFLAGS" ;; esac expr "x$DEBUG" : '.*-O' > /dev/null \ || sfs_gnu_WFLAGS="$sfs_gnu_WFLAGS -Wno-unused" expr "x$CXXDEBUG" : '.*-O' > /dev/null \ || sfs_gnu_CXXWFLAGS="$sfs_gnu_CXXWFLAGS -Wno-unused" NW='-w' test "$GCC" = yes -a -z "${WFLAGS+set}" && WFLAGS="$sfs_gnu_WFLAGS" test "$GXX" = yes -a -z "${CXXWFLAGS+set}" && CXXWFLAGS="$sfs_gnu_CXXWFLAGS" CXXNOERR= test "$GXX" = yes && CXXNOERR='-Wno-error' # Temporarily set CFLAGS to ansi so tests for things like __inline go correctly if expr "x$DEBUG $WFLAGS $ECFLAGS" : '.*-ansi' > /dev/null; then CFLAGS="$CFLAGS -ansi" ac_cpp="$ac_cpp -ansi" fi expr "x$CXXDEBUG $CXXWFLAGS $ECXXFLAGS" : '.*-ansi' > /dev/null \ && CXXFLAGS="$CXXFLAGS -ansi" ]) dnl dnl SFS_CFLAGS puts the effects of SFS_WFLAGS into place. dnl This must be called after all tests have been run. dnl AC_DEFUN([SFS_CFLAGS], [unset CFLAGS unset CXXFLAGS CFLAGS='$(DEBUG) $(WFLAGS) $(ECFLAGS)' CXXFLAGS='$(CXXDEBUG) $(CXXWFLAGS) $(ECXXFLAGS)']) dnl dnl Check for xdr_u_intNN_t, etc dnl AC_DEFUN([SFS_CHECK_XDR], [ dnl AC_CACHE_CHECK([for a broken ], sfs_cv_xdr_broken, dnl AC_EGREP_HEADER(xdr_u_int32_t, [rpc/xdr.h], dnl sfs_cv_xdr_broken=no, sfs_cv_xdr_broken=yes)) dnl if test "$sfs_cv_xdr_broken" = "yes"; then dnl AC_DEFINE(SFS_XDR_BROKEN) dnl dnl We need to know the following in order to fix rpc/xdr.h: dnl AC_CHECK_SIZEOF(short) dnl AC_CHECK_SIZEOF(int) dnl AC_CHECK_SIZEOF(long) dnl fi SFS_CHECK_DECL(xdr_callmsg, rpc/rpc.h) AC_CACHE_CHECK(what second xdr_getlong arg points to, sfs_cv_xdrlong_t, AC_EGREP_HEADER(\*x_getlong.* long *\*, [rpc/rpc.h], sfs_cv_xdrlong_t=long) if test -z "$sfs_cv_xdrlong_t"; then AC_EGREP_HEADER(\*x_getlong.* int *\*, [rpc/rpc.h], sfs_cv_xdrlong_t=int) fi if test -z "$sfs_cv_xdrlong_t"; then sfs_cv_xdrlong_t=u_int32_t fi) AC_DEFINE_UNQUOTED(xdrlong_t, $sfs_cv_xdrlong_t, What the second argument of xdr_getlong points to) ]) dnl dnl Check for random device dnl AC_DEFUN([SFS_DEV_RANDOM], [AC_CACHE_CHECK([for kernel random number generator], sfs_cv_dev_random, for dev in /dev/urandom /dev/srandom /dev/random /dev/srnd /dev/rnd; do if test -c "$dev"; then sfs_cv_dev_random=$dev break fi test "$sfs_cv_dev_random" || sfs_cv_dev_random=no done) if test "$sfs_cv_dev_random" != no; then pushdef([SFS_DEV_RANDOM], [[SFS_DEV_RANDOM]]) AC_DEFINE_UNQUOTED([SFS_DEV_RANDOM], "$sfs_cv_dev_random", [Path to the strongest random number device, if any.]) popdef([SFS_DEV_RANDOM]) fi ]) dnl dnl Check for getgrouplist function dnl AC_DEFUN([SFS_GETGROUPLIST_TRYGID], [ if test "$sfs_cv_grouplist_t" != gid_t; then AC_TRY_COMPILE([ #include #include #include int getgrouplist ([$*]); ], 0, sfs_cv_grouplist_t=gid_t) fi ]) AC_DEFUN([SFS_GETGROUPLIST], [AC_CHECK_FUNCS(getgrouplist) AC_CACHE_CHECK([whether getgrouplist uses int or gid_t], sfs_cv_grouplist_t, if test "$ac_cv_func_getgrouplist" = yes; then sfs_cv_grouplist_t=int AC_EGREP_HEADER(getgrouplist.*gid_t *\*, unistd.h, sfs_cv_grouplist_t=gid_t) if test "$sfs_cv_grouplist_t" != gid_t; then AC_EGREP_HEADER(getgrouplist.*gid_t *\*, grp.h, sfs_cv_grouplist_t=gid_t) fi SFS_GETGROUPLIST_TRYGID(const char *, gid_t, gid_t *, int *) SFS_GETGROUPLIST_TRYGID(const char *, int , gid_t *, int *) SFS_GETGROUPLIST_TRYGID(char *, gid_t, gid_t *, int *) SFS_GETGROUPLIST_TRYGID(char *, int, gid_t *, int *) else sfs_cv_grouplist_t=gid_t fi) AC_DEFINE_UNQUOTED([GROUPLIST_T], $sfs_cv_grouplist_t, [Type pointed to by 3rd argument of getgrouplist.])]) dnl dnl Check if is needed for setgroups declaration (linux) dnl AC_DEFUN([SFS_SETGROUPS], [AC_CACHE_CHECK([for setgroups declaration in grp.h], sfs_cv_setgroups_grp_h, AC_EGREP_HEADER(setgroups, grp.h, sfs_cv_setgroups_grp_h=yes, sfs_cv_setgroups_grp_h=no)) if test "$sfs_cv_setgroups_grp_h" = yes; then AC_DEFINE([SETGROUPS_NEEDS_GRP_H], 1, [Define if setgroups is declared in .]) fi]) dnl dnl Check if authunix_create is broken and takes a gid_t * dnl AC_DEFUN([SFS_AUTHUNIX_GROUP_T], [AC_CACHE_CHECK([what last authunix_create arg points to], sfs_cv_authunix_group_t, AC_EGREP_HEADER([(authunix|authsys)_create.*(uid_t|gid_t)], rpc/rpc.h, sfs_cv_authunix_group_t=gid_t, sfs_cv_authunix_group_t=int)) if test "$sfs_cv_authunix_group_t" = gid_t; then AC_DEFINE_UNQUOTED(AUTHUNIX_GID_T, 1, [Define if last argument of authunix_create is a gid_t *.]) fi]) dnl dnl Check the type of the x_ops field in XDR dnl AC_DEFUN([SFS_XDR_OPS_T], [AC_CACHE_CHECK([type of XDR::x_ops], sfs_cv_xdr_ops_t, AC_EGREP_HEADER([xdr_ops *\* *x_ops;], rpc/xdr.h, sfs_cv_xdr_ops_t=xdr_ops, sfs_cv_xdr_ops_t=XDR::xdr_ops)) AC_DEFINE_UNQUOTED(xdr_ops_t, $sfs_cv_xdr_ops_t, [The C++ type name of the x_ops field in struct XDR.])]) dnl dnl Find installed SFS libraries dnl This is not for SFS, but for other packages that use SFS. dnl AC_DEFUN([SFS_SFS], [AC_ARG_WITH(sfs, --with-sfs[[=PATH]] specify location of SFS libraries) if test "$with_sfs" = yes -o "$with_sfs" = ""; then for dir in "$prefix" /usr/local /usr; do if test -f $dir/lib/sfs/libasync.la; then with_sfs=$dir break fi done fi case "$with_sfs" in /*) ;; *) with_sfs="$PWD/$with_sfs" ;; esac if test -f ${with_sfs}/Makefile -a -f ${with_sfs}/autoconf.h; then if egrep '#define DMALLOC' ${with_sfs}/autoconf.h > /dev/null 2>&1; then test -z "$with_dmalloc" -o "$with_dmalloc" = no && with_dmalloc=yes elif test "$with_dmalloc" -a "$with_dmalloc" != no; then AC_MSG_ERROR("SFS libraries not compiled with dmalloc") fi sfssrcdir=`sed -ne 's/^srcdir *= *//p' ${with_sfs}/Makefile` case "$sfssrcdir" in /*) ;; *) sfssrcdir="${with_sfs}/${sfssrcdir}" ;; esac CPPFLAGS="$CPPFLAGS -I${with_sfs}" for lib in async arpc crypt sfsmisc; do CPPFLAGS="$CPPFLAGS -I${sfssrcdir}/$lib" done CPPFLAGS="$CPPFLAGS -I${with_sfs}/svc" LIBASYNC=${with_sfs}/async/libasync.la LIBARPC=${with_sfs}/arpc/libarpc.la LIBSFSCRYPT=${with_sfs}/crypt/libsfscrypt.la LIBSFSMISC=${with_sfs}/sfsmisc/libsfsmisc.la LIBSVC=${with_sfs}/svc/libsvc.la LIBSFS=${with_sfs}/libsfs/libsfs.la MALLOCK=${with_sfs}/sfsmisc/mallock.o RPCC=${with_sfs}/rpcc/rpcc elif test -f ${with_sfs}/include/sfs/autoconf.h \ -a -f ${with_sfs}/lib/sfs/libasync.la; then sfsincludedir="${with_sfs}/include/sfs" sfslibdir=${with_sfs}/lib/sfs if egrep '#define DMALLOC' ${sfsincludedir}/autoconf.h > /dev/null; then test -z "$with_dmalloc" -o "$with_dmalloc" = no && with_dmalloc=yes else with_dmalloc=no fi CPPFLAGS="$CPPFLAGS -I${sfsincludedir}" LIBASYNC=${sfslibdir}/libasync.la LIBARPC=${sfslibdir}/libarpc.la LIBSFSCRYPT=${sfslibdir}/libsfscrypt.la LIBSFSMISC=${sfslibdir}/libsfsmisc.la LIBSVC=${sfslibdir}/libsvc.la LIBSFS=${with_sfs}/lib/libsfs.a MALLOCK=${sfslibdir}/mallock.o RPCC=${with_sfs}/bin/rpcc else AC_MSG_ERROR("Can\'t find SFS libraries") fi if test "$enable_static" = yes -a -z "${NOPAGING+set}"; then case "$host_os" in openbsd*) test "$ac_cv_prog_gcc" = yes && NOPAGING="-Wl,-Bstatic,-N" MALLOCK= # mallock.o panics the OpenBSD kernel ;; freebsd*) test "$ac_cv_prog_gcc" = yes && NOPAGING="-Wl,-Bstatic" ;; esac fi sfslibdir='$(libdir)/sfs' sfsincludedir='$(libdir)/include' AC_SUBST(sfslibdir) AC_SUBST(sfsincludedir) AC_SUBST(LIBASYNC) AC_SUBST(LIBARPC) AC_SUBST(LIBSFSCRYPT) AC_SUBST(LIBSFSMISC) AC_SUBST(LIBSVC) AC_SUBST(LIBSFS) AC_SUBST(RPCC) AC_SUBST(MALLOCK) AC_SUBST(NOPAGING) SFS_GMP SFS_DMALLOC LDEPS='$(LIBSFSMISC) $(LIBSVC) $(LIBSFSCRYPT) $(LIBARPC) $(LIBASYNC)' LDADD="$LDEPS "'$(LIBGMP)' AC_SUBST(LDEPS) AC_SUBST(LDADD) ]) avenger-0.8.5/AUTHORS0000644000175000017500000000003411221235216011134 00000000000000David Mazieres (dm@uun.org) avenger-0.8.5/config.h.in0000644000175000017500000002325113357046453012134 00000000000000/* config.h.in. Generated from configure.in by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* Define if compiling with dmalloc. */ #undef DMALLOC /* Define to the type of elements in the array set by `getgroups'. Usually this is either `int' or `gid_t'. */ #undef GETGROUPS_T /* Type pointed to by 3rd argument of getgrouplist. */ #undef GROUPLIST_T /* Define if msghdr has msg_accrights field for passing file descriptors. */ #undef HAVE_ACCRIGHTS /* Define to 1 if you have the `arc4random' function. */ #undef HAVE_ARC4RANDOM /* Define to 1 if you have the header file. */ #undef HAVE_ARPA_NAMESER_COMPAT_H /* Define to 1 if you have the `bindresvport' function. */ #undef HAVE_BINDRESVPORT /* Define if system headers declare a bpf_u_int32 type. */ #undef HAVE_BPF_U_INT32 /* Define to 1 if you have the `clock_gettime' function. */ #undef HAVE_CLOCK_GETTIME /* Define if system headers declare clock_gettime. */ #undef HAVE_CLOCK_GETTIME_DECL /* Define if system has cmsghdr structure for passing file descriptors. */ #undef HAVE_CMSGHDR /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define if the first element of a grouplist is the effective gid */ #undef HAVE_EGID_IN_GROUPLIST /* Define to 1 if you have the `flock' function. */ #undef HAVE_FLOCK /* Define to 1 if you have the `getdtablesize' function. */ #undef HAVE_GETDTABLESIZE /* Define to 1 if you have the `getegid' function. */ #undef HAVE_GETEGID /* Define to 1 if you have the `geteuid' function. */ #undef HAVE_GETEUID /* Define to 1 if you have the `getgrouplist' function. */ #undef HAVE_GETGROUPLIST /* Define to 1 if you have the `getpeereid' function. */ #undef HAVE_GETPEEREID /* Define to 1 if you have the `getspnam' function. */ #undef HAVE_GETSPNAM /* Define to 1 if you have the `inet_aton' function. */ #undef HAVE_INET_ATON /* Define to 1 if you have the `initgroups' function. */ #undef HAVE_INITGROUPS /* Define if system headers declare a int32_t type. */ #undef HAVE_INT32_T /* Define if system headers declare a int64_t type. */ #undef HAVE_INT64_T /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `issetugid' function. */ #undef HAVE_ISSETUGID /* Define to 1 if you have the header file. */ #undef HAVE_LOGIN_CAP_H /* Define to 1 if you have the `memcpy' function. */ #undef HAVE_MEMCPY /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the `mkdtemp' function. */ #undef HAVE_MKDTEMP /* Define if system headers declare a mode_t type. */ #undef HAVE_MODE_T /* Define if you have dbm/ndbm */ #undef HAVE_NDBM /* Define if off_t is 64 bits wide. */ #undef HAVE_OFF_T_64 /* Define if struct passwd has pw_class field */ #undef HAVE_PASSWD_PW_CLASS /* Define if struct passwd has pw_expire field */ #undef HAVE_PASSWD_PW_EXPIRE /* Define to 1 if you have the `pcap_freecode' function. */ #undef HAVE_PCAP_FREECODE /* Define to 1 if you have the header file. */ #undef HAVE_PCAP_H /* Define if system headers declare a rlim_t type. */ #undef HAVE_RLIM_T /* Define to 1 if you have the header file. */ #undef HAVE_RPC_RPC_H /* Define if struct sockaddr has sa_len field. */ #undef HAVE_SA_LEN /* Define to 1 if you have the `seteuid' function. */ #undef HAVE_SETEUID /* Define to 1 if you have the `setlogin' function. */ #undef HAVE_SETLOGIN /* Define if you have the setusercontext function */ #undef HAVE_SETUSERCONTEXT /* Define if system headers declare a socklen_t type. */ #undef HAVE_SOCKLEN_T /* Define if system headers declare a ssize_t type. */ #undef HAVE_SSIZE_T /* Define if struct sockaddr_storage has __ss_len field */ #undef HAVE_SS_LEN_UNDERSCORES /* 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 `strcasecmp' function. */ #undef HAVE_STRCASECMP /* Define to 1 if you have the `strchr' function. */ #undef HAVE_STRCHR /* Define to 1 if you have the `strerror' function. */ #undef HAVE_STRERROR /* 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 if system headers declare a struct sockaddr_storage type. */ #undef HAVE_STRUCT_SOCKADDR_STORAGE /* Define to 1 if you have the header file. */ #undef HAVE_SYS_FILE_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_FILIO_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_RUSAGE_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_SOCKIO_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 if sys/time.h defines a struct timespec. */ #undef HAVE_TIMESPEC /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the `unsetenv' function. */ #undef HAVE_UNSETENV /* Define if system headers declare a u_char type. */ #undef HAVE_U_CHAR /* Define if system headers declare a u_int type. */ #undef HAVE_U_INT /* Define if system headers declare a u_int16_t type. */ #undef HAVE_U_INT16_T /* Define if system headers declare a u_int32_t type. */ #undef HAVE_U_INT32_T /* Define if system headers declare a u_int64_t type. */ #undef HAVE_U_INT64_T /* Define if system headers declare a u_int8_t type. */ #undef HAVE_U_INT8_T /* Define if system headers declare a u_long type. */ #undef HAVE_U_LONG /* Define if select can take file descriptors >= FD_SETSIZE */ #undef HAVE_WIDE_SELECT /* Define to 1 if you have the `__res_ninit' function. */ #undef HAVE___RES_NINIT /* Define to the sub-directory where libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Define if system headers do not declare bindresvport. */ #undef NEED_BINDRESVPORT_DECL /* Define if system headers do not declare dn_expand. */ #undef NEED_DN_EXPAND_DECL /* Define if system headers do not declare dn_skipname. */ #undef NEED_DN_SKIPNAME_DECL /* Define if system headers do not declare getrusage. */ #undef NEED_GETRUSAGE_DECL /* Define if system headers do not declare pread. */ #undef NEED_PREAD_DECL /* Define if system headers do not declare pwrite. */ #undef NEED_PWRITE_DECL /* Define if system headers do not declare res_init. */ #undef NEED_RES_INIT_DECL /* Define if system headers do not declare res_mkquery. */ #undef NEED_RES_MKQUERY_DECL /* Define if system headers do not declare sys_signame. */ #undef NEED_SYS_SIGNAME_DECL /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Full path of logger command */ #undef PATH_LOGGER /* Full path of mail.local command */ #undef PATH_MAIL_LOCAL /* Define if putenv makes a copy of its argument */ #undef PUTENV_COPIES_ARGUMENT /* Define to use Cyrus libsasl2. */ #undef SASL /* Define if setgroups is declared in . */ #undef SETGROUPS_NEEDS_GRP_H /* Define if SO_SNDBUF/SO_RCVBUF can exceed 64K. */ #undef SFS_ALLOW_LARGE_BUFFER /* Path to the strongest random number device, if any. */ #undef SFS_DEV_RANDOM /* Define if the stat structure has a st_atimespec field. */ #undef SFS_HAVE_STAT_ST_ATIMESPEC /* Define if the stat structure has a st_mtim field. */ #undef SFS_HAVE_STAT_ST_MTIM /* Define if the stat structure has a st_mtimespec field. */ #undef SFS_HAVE_STAT_ST_MTIMESPEC /* The size of `long', as computed by sizeof. */ #undef SIZEOF_LONG /* The size of `long long', as computed by sizeof. */ #undef SIZEOF_LONG_LONG /* Define to implement STARTTLS command. */ #undef STARTTLS /* 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 include code for TCP SYN fingerprints */ #undef USE_SYNFP /* Define if system header files typedef u_int64_t as unsigned long long */ #undef U_INT64_T_IS_LONG_LONG /* Version number of package */ #undef VERSION /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to empty if `const' does not conform to ANSI C. */ #undef const /* Define to `int' if doesn't define. */ #undef gid_t /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif /* Define to `long int' if does not define. */ #undef off_t /* Define to `unsigned int' if does not define. */ #undef size_t /* Define to `int' if doesn't define. */ #undef uid_t avenger-0.8.5/doc/0000755000175000017500000000000013357046620010727 500000000000000avenger-0.8.5/doc/Makefile.in0000644000175000017500000005516713357046343012734 00000000000000# Makefile.in generated by automake 1.15.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2017 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = { \ if test -z '$(MAKELEVEL)'; then \ false; \ elif test -n '$(MAKE_HOST)'; then \ true; \ elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ true; \ else \ false; \ fi; \ } am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = doc ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \ $(top_srcdir)/configure.in am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) DIST_COMMON = $(srcdir)/Makefile.am $(am__DIST_COMMON) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 am__installdirs = "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man5dir)" \ "$(DESTDIR)$(man8dir)" man5dir = $(mandir)/man5 man8dir = $(mandir)/man8 NROFF = nroff MANS = $(man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__DIST_COMMON = $(srcdir)/Makefile.in DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEBUG = @CXXDEBUG@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CXXNOERR = @CXXNOERR@ CXXWFLAGS = @CXXWFLAGS@ CYGPATH_W = @CYGPATH_W@ DB_DIR = @DB_DIR@ DB_LIB = @DB_LIB@ DEBUG = @DEBUG@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECFLAGS = @ECFLAGS@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ ECXXFLAGS = @ECXXFLAGS@ EGREP = @EGREP@ ETAGS_ARGS = @ETAGS_ARGS@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDADD = @LDADD@ LDEPS = @LDEPS@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBPCAP = @LIBPCAP@ LIBS = @LIBS@ LIBSASL = @LIBSASL@ LIBSSL = @LIBSSL@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NDBM_INC = @NDBM_INC@ NDBM_LIBS = @NDBM_LIBS@ NM = @NM@ NMEDIT = @NMEDIT@ NW = @NW@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_LOGGER = @PATH_LOGGER@ PATH_MAIL_LOCAL = @PATH_MAIL_LOCAL@ PATH_SEPARATOR = @PATH_SEPARATOR@ PERL = @PERL@ PERL_POD_MAN = @PERL_POD_MAN@ POD2MAN = @POD2MAN@ RANLIB = @RANLIB@ SED = @SED@ SETUSERCONTEXTLIB = @SETUSERCONTEXTLIB@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ STRIP = @STRIP@ VERSION = @VERSION@ WFLAGS = @WFLAGS@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ docdir = @docdir@ dvidir = @dvidir@ etcdir = @etcdir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ piddir = @piddir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sampledir = @sampledir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ srcdir = @srcdir@ subdirs = @subdirs@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ man_MANS = aliascheck.1 avenger.1 dbutil.1 deliver.1 dotlock.1 \ edinplace.1 escape.1 macutil.1 mailexec.1 match.1 smtpdcheck.1 synos.1 \ asmtpd.conf.5 asmtpd.8 avenger.local.8 SUFFIXES = .pod .1 .5 .8 .html MAN_RULE = rm -f $@; \ sec=`expr $@ : '.*\.\([^.]\)$$'`; \ sed -e 's!@'etcdir'@!$(etcdir)!g' \ -e 's!@'libexecdir'@!$(libexecdir)!g' \ -e 's!@'datadir'@!$(datadir)!g' \ -e 's!@'sampledir'@!$(sampledir)!g' \ -e 's!@'piddir'@!$(piddir)!g' < $< \ -e 's!@'VERSION'@!$(VERSION)!g' < $< \ | $(POD2MAN) --release="Mail Avenger $(VERSION)" \ --center="Mail Avenger $(VERSION)" \ --name=`basename $@ .$$sec`\ --section=$$sec \ | perl -pe 's/([^\\])-/$1\\-/g if (/^\\\\& /);' > $@ GROFF = groff HTML_RULE = $(GROFF) -Thtml -P -l -man $< > $@ EXTRA_DIST = .gitignore aliascheck.pod asmtpd.conf.pod asmtpd.pod \ avenger.local.pod avenger.pod dbutil.pod deliver.pod dotlock.pod \ edinplace.pod escape.pod macutil.pod mailexec.pod match.pod \ smtpdcheck.pod synos.pod CLEANFILES = core *.core *~ *.html pod2htm[di].tmp #DISTCLEANFILES = MAINTAINERCLEANFILES = Makefile.in $(man_MANS) $(srcdir)/*.[158] all: all-am .SUFFIXES: .SUFFIXES: .pod .1 .5 .8 .html $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu doc/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --gnu doc/Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) install-man5: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man5dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man5dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man5dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.5[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \ done; } uninstall-man5: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man5dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.5[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man5dir)'; $(am__uninstall_files_from_dir) install-man8: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man8dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man8dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man8dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.8[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man8dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man8dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man8dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man8dir)" || exit $$?; }; \ done; } uninstall-man8: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man8dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.8[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^8][0-9a-z]*$$,8,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man8dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$(top_distdir)" distdir="$(distdir)" \ dist-hook check-am: all-am check: check-am all-am: Makefile $(MANS) installdirs: for dir in "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man5dir)" "$(DESTDIR)$(man8dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-am dvi-am: html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-man5 install-man8 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-man uninstall-man: uninstall-man1 uninstall-man5 uninstall-man8 .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ clean-libtool cscopelist-am ctags ctags-am dist-hook distclean \ distclean-generic distclean-libtool distclean-tags distdir dvi \ dvi-am html html-am info info-am install install-am \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-man1 \ install-man5 install-man8 install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am uninstall-man uninstall-man1 uninstall-man5 \ uninstall-man8 .PRECIOUS: Makefile .pod.1: $(MAN_RULE) .pod.5: $(MAN_RULE) .pod.8: $(MAN_RULE) .1.html: $(HTML_RULE) .5.html: $(HTML_RULE) .8.html: $(HTML_RULE) .PHONY: man man: $(man_MANS) .PHONY: dist-hook dist-hook: $(MAKE) manclean man for man in $(man_MANS); do \ if test -f $$man; then \ cp $$man $(distdir)/; \ elif test -f $(srcdir)/$$man; then \ cp $(srcdir)/$$man $(distdir)/; \ fi \ done .PHONY: html html: aliascheck.html asmtpd.conf.html asmtpd.html avenger.local.html \ avenger.html dbutil.html deliver.html dotlock.html edinplace.html \ escape.html macutil.html match.html mailexec.html smtpdcheck.html \ synos.html .PHONY: manclean manclean: -rm -f $(man_MANS) $(srcdir)/*.[158] # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: avenger-0.8.5/doc/avenger.local.80000644000175000017500000006302413357046620013465 00000000000000.\" Automatically generated by Pod::Man 4.10 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "avenger.local 8" .TH avenger.local 8 "2018-10-09" "Mail Avenger 0.8.5" "Mail Avenger 0.8.5" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" avenger.local \- deliver mail for a local user .SH "SYNOPSIS" .IX Header "SYNOPSIS" avenger.local [\-f \fIsender\fR] [\-D \fIrecip\fR] [\-a \fIextra\fR] [\-d] \fIuser\fR .SH "DESCRIPTION" .IX Header "DESCRIPTION" avenger.local is a local mail delivery agent that enables users to set up multiple \*(L"extension\*(R" email addresses and process mail differently for each addresses. The popular qmail \s-1MTA\s0 () has a mechanism for processing such extension addresses. avenger.local provides a similar facility for users of other MTAs, such as sendmail. .PP To use avenger.local, you should configure your \s-1MTA\s0 so that it delivers mail to \fIuser\fR\fB+\fR\fIextra\fR\fB@\fR\fIhost\fR by executing \&\fBavenger.local\fR \fB\-D\fR \fIuser\fR\fB+\fR\fIextra\fR\fB@\fR\fIhost\fR \fB\-d\fR \&\fIuser\fR\fB+\fR\fIextra\fR. Alternatively, you can execute \fBavenger.local\fR \&\fB\-a\fR \fIextra\fR \fB\-d\fR \fIuser\fR, but then you lose information about the host. However, the latter syntax has the advantage of being command-line compatible with procmail; thus, if your \s-1MTA\s0 has support for procmail as a local delivery agent, you should be able to use that by simply substituting avenger.local's path for procmail's. .PP Note that either way you invoke it, avenger.local rejects recipients containing the string \f(CW\*(C`..\*(C'\fR in the local part. Such mailbox names are not allowed by \s-1RFC822,\s0 and could potentially lead to security problems if parts of mailbox names are used as file names. Out of paranoia, avenger.local additionally rejects mailbox names containing the \f(CW\*(C`/\*(C'\fR character in the extra portion after the local username. .PP avenger.local is designed to be unobtrusive for users who do not want to take advantage of its functionality. When delivering mail for \&\fIuser\fR, if \fIuser\fR's home directory does not contain a subdirectory \&\fI.avenger\fR, avenger.local simply executes the default mail delivery agent (usually called \fImail.local\fR). .PP For users who do have \fI.avenger\fR directories, mail is delivered according to rule files called \fI.avenger/local*\fR. Mail to \&\fIuser\fR\fB@\fR\fIhost\fR is delivered according to rules in \&\fI.avenger/local\fR. Mail to \fIuser\fR\fB+\fR\fIext1\fR\fB@\fR\fIhost\fR is delivered according to rules in \fI.avenger/local+ext1\fR if such a file exists, or else \fI.avenger/local+default\fR if such a file exists; if neither file exists, the mail is bounced. Addresses containing multiple \f(CW\*(C`+\*(C'\fR characters are handled as expected. Mail to \&\fIuser\fR\fB+\fR\fIext1\fR\fB+\fR\fIext2\fR\fB@\fR\fIhost\fR is governed by, in order of decreasing precedence, \fI.avenger/local+ext1+ext2\fR, \&\fI.avenger/local+ext1+default\fR, or \fI.avenger/local+default\fR; it is bounced if none of those files exist. .PP Local rule files can be in one of two formats. If the first two characters of the file are \f(CW\*(C`#!\*(C'\fR, then the file is simply executed as a script, with the message on standard input. The script's standard input will be read-only, but seekable, so, for example, the message can be delivered to multiple mailboxes using the deliver utility. .PP Otherwise, if the first two characters of a file are not \f(CW\*(C`#!\*(C'\fR, avenger.local uses a syntax similar to (but not identical to) qmail's, where each line is one of the following types, depending on the first character: .IP "\fB#\fR \fIcomment\fR" 4 .IX Item "# comment" Lines starting with \f(CW\*(C`#\*(C'\fR are treated as comments and ignored. The exception is that if the first line begins \f(CW\*(C`#!\*(C'\fR, the file is executed as a script. Note that if the first two characters of a file are \&\f(CW\*(C`#!\*(C'\fR but the file's execute permission bits are not set, then mail sent to that address will be deferred. (This mechanism can be used for intentionally deferring mail while performing maintenance.) .IP "\fI./maildir/\fR" 4 .IX Item "./maildir/" .PD 0 .IP "\fI/path/to/maildir/\fR" 4 .IX Item "/path/to/maildir/" .PD A line starting \f(CW\*(C`.\*(C'\fR or \f(CW\*(C`/\*(C'\fR and ending with a \f(CW\*(C`/\*(C'\fR character is treated as a mail directory. Mail is delivered there using the qmail maildir format. .IP "\fI./file\fR" 4 .IX Item "./file" .PD 0 .IP "\fI/path/to/file\fR" 4 .IX Item "/path/to/file" .PD A line starting \f(CW\*(C`.\*(C'\fR or \f(CW\*(C`/\*(C'\fR and \s-1NOT\s0 ending with a \f(CW\*(C`/\*(C'\fR character specifies an ordinary Unix mbox file into which the message should be delivered. .IP "\fB&\fR\fIaddress\fR" 4 .IX Item "&address" \&\f(CW\*(C`&\*(C'\fR indicates that a copy of the message should be forwarded to \&\fIaddress\fR. You may not place a space between \fB&\fR and address, nor can \fIaddress\fR contain angle brackets, comments, or anything other than an email address with a fully-qualified domain name. .Sp (Note that in qmail, the \fB&\fR character is optional for certain email addresses, while avenger.local always requires the \fB&\fR character.) .Sp Forwarding happens after all other lines in the file are processed. If any other configuration line fails, for instance because a command executed on behalf of a \fB|\fR line exits non-zero, the mail is not forwarded to any of the addresses. (The exception is if a command exits with status 99, in which case mail is forwarded to addresses in all preceding \fB&\fR lines, but subsequent lines are ignored.) .IP "\fB|\fR \fIcommand\fR" 4 .IX Item "| command" Specifies that \fIcommand\fR should be run as a shell command, with the mail message as its standard input. If \fIcommand\fR exits with a status other than 0, processing of the local rule file terminates immediately, with avenger.local's exit status determined by \&\fIcommand\fR's. .Sp If \fIcommand\fR's status is 99, avenger.local exits with status 0, effectively pretending the command just executed was the last line in the \fI.avenger/local*\fR file. If \fIcommand\fR's exit status is between 64 and 78, inclusive, avenger.local exits with the same status as \&\fIcommand\fR. If \fIcommand\fR exits with status 100 or 112, avenger.local exits with status 70. For all other exit values, or if \fIcommand\fR terminates because of a signal, avenger.local exits with status 75. Note that the \fB\-\-qmailexit\fR flag changes this behavior, as described below. .Sp See the file \fI/usr/include/sysexits.h\fR for more information on the meaning of various exit statuses to sendmail. .IP "\fB<\fR\fIaddress\fR" 4 .IX Item ". .SH "BUGS" .IX Header "BUGS" avenger.local doesn't necessarily report problems in a the most useful place when it encounters errors in a \fI.avenger/local*\fR file. It does send some diagnostics to standard error, but these will typically end up in the mail log or in bounce messages returned to the sender. .PP avenger.local should always provide the exact envelope recipient in the \fB\s-1RECIPIENT\s0\fR environment variable. Unfortunately, this information is not available unless it has been supplied with the \&\fB\-D\fR flag. Often the envelope recipient is just "\fB${\s-1USER\s0}${\s-1SEPARATOR\s0}${\s-1EXT\s0}@your.host.name\fR", but it might not be if there are aliases or virtual domains. On servers with virtual hosts, the actual hostname used will be unavailable in the general case (though you may be able to deduce it from \fB\f(CB$USER\fB\fR and \fB\f(CB$EXT\fB\fR if you know your particular setup). Note that it is possible to configure sendmail to supply the full recipient address. Mail avenger comes with example sendmail configuration directives that can be included in your \fIsendmail.mc\fR m4 configuration file; see \&\fI/usr/local/share/avenger/avsendmail.m4\fR. .PP To protect against concurrent accesses to mbox format files, avenger.local uses both \fIflock\fR and dotfiles to lock mailboxes. However, it does not use \fIfcntl\fR/\fIlockf\fR\-style locking by default. Thus, if your mail reader exclusively uses \fIfcntl\fR for locking, there will be race conditions unless you specify the \fB\-\-fcntl\fR option. .SH "AUTHOR" .IX Header "AUTHOR" David Mazie\*`res avenger-0.8.5/doc/macutil.pod0000644000175000017500000002014611221235216013001 00000000000000=for comment $Id$ =head1 NAME macutil, sendmac - Message Authentication Code utility =head1 SYNOPSIS macutil --gen [I] macutil --sender [I